In this lesson, you will learn how to create an exception in Java.
We already have a number of defined Exception classes, which will be triggered in special conditions. For example, if an error occurs while working with files, IOException will be thrown. Or, if a number is divided by zero, the ArithmeticException will be thrown.
We can also define our own custom Exception classes. All we have to do is create a new class, name it as we wish, and inherit one of the existing Exception classes, such as Exception.class or RuntimeException.class. Or any other class that is a subclass of these classes.
How to create a custom exception in Java?
See an example of creating a custom Exception class:
public class MyCustomException extends RuntimeException { public MyCustomException(String message) { super(message); } }
Here we created the MyCustomException class that inherits the RuntimeException. We then defined one constructor that would take the string as a parameter and call the constructor from the superclass, using the super keyword. See more about the super keyword in Java → Keyword super in Java.
We had to define a constructor to pass a meaningful message to it when explicitly throwing an exception.
Example of using a custom exception:
class Test { public static void main(String[] args) { Test test = new Test(); try { test.reserveSeats(8); } catch (MyCustomException e) { System.out.println("Exception occurred with message: " + e.getMessage()); } } private void reserveSeats(int numberOfSeats) { if (numberOfSeats > 5) { throw new IllegalArgumentException("No more than 5 seats can be reserved."); } else { System.out.println("Reservation successful!"); } } }