How to throw an exception in Java?
We can throw an exception in Java using the keyword throw.
So far, we have learned that we can get different exceptions during program execution, depending on what errors we have in our code.
For example, when we divide a number by zero, this triggers ArithmeticException. When we try to access the array element out of its bounds, then we get ArrayIndexOutOfBoundsException.
Also, we can make our code explicitly throw an exception based on conditions that we define.
The syntax of Java throw keyword:
throw new Exception();
Example of using the throw keyword in Java
Let’s write a program that accepts reservations for a movie that is not for younger viewers than 18 years old. If a reservation arrives for a user under the age of 18, we will explicitly throw an IllegalArgumentException. The IllegalArgumentException indicates that a method has been passed an illegal or inappropriate argument.
class Test { public static void main(String[] args) { reserveSeat(new User("Steve", "Johnson", false, 32)); // OK reserveSeat(new User("Mike", "Lawson", true, 16)); // Exception will occur } private static void reserveSeat(User user) { if (user.getAge() < 18) { throw new IllegalArgumentException("The user is under 18 years old!"); } } } class User { // fields private String firstName; private String lastName; private boolean premiumMember; private int age; // Constructor public User(String firstName, String lastName, boolean premiumMember, int age) { this.firstName = firstName; this.lastName = lastName; this.premiumMember = premiumMember; this.age = age; } // Getter method public int getAge() { return age; } }