In Java we have already defined exception classes such as ArithmeticException, NullPointerException, ArrayIndexOutOfBounds exception etc. These exceptions are set to trigger on different conditions. 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.
The Java throw keyword is used to throw an exception explicitly. We specify the exception object which is to be thrown. The Exception has some message with it that provides the error description. These exceptions may be related to user inputs, server, etc.
We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used to throw a custom exception.
throw Instance
Example:
throw new ArithmeticException("/ by zero");
Instance must be of type Throwable or a subclass of Throwable. For example Exception is a sub-class of Throwable and user defined exceptions typically extend Exception class.Data types such as int, char, floats or non-throwable classes cannot be used as exceptions.
The flow of execution of the program stops immediately after the throw statement is executed and the nearest enclosing try block is checked to see if it has a catch statement that matches the type of exception. If it finds a match, controlled is transferred to that statement otherwise next enclosing try block is checked and so on. If no matching catch is found then the default exception handler will halt the program.
public class Example1 {
public static void test() {
try {
throw new ArithmeticException(" Hello ");
} catch (ArithmeticException e) {
System.out.println("Caught throw exception in method.");
throw e; // rethrowing the exception
}
}
public static void main(String args[]) {
try {
test();
} catch (ArithmeticException e) {
System.out.println("Caught exception in main.");
}
}
}
Output
Caught throw exception in method.
Caught exception in main.
Let us take another example where we have created the validate method that takes integer value as a parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a message “Person is eligible to drive!!” .
public class Example1 {
public static void validate(int age) {
if (age < 18) {
// throw Arithmetic exception if not eligible to drive
throw new ArithmeticException("Person is not eligible to drive");
} else {
System.out.println("Person is eligible to drive!!");
}
}
public static void main(String args[]) {
validate(13);
}
}
Exception in thread "main" java.lang.ArithmeticException: Person is not eligible to drive
at ExceptionsExamples.Example1.validate(Example1.java:9)
at ExceptionsExamples.Example1.main(Example1.java:16)
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!