Java Exceptions  «Prev  Next»

Lesson 7Throw your own exception in Java
ObjectiveThrow an exception in Java.

Throw your own Exceptions in Java

In addition to simply handling Java's exceptions, you can also throw your own exception.
Here is an example of using the throw keyword. If you are performing a calculation that might involve some division, you might wish to perform a check to see if the divisor is zero (0), and if it is, throw an exception, as in:

double calcResult(double divisor, double dividend) 
  throws ArithmeticException {  
    if (divisor == 0)  
      throw new ArithmeticException();  
    else  
      return dividend/divisor;  
 }

Notice how we must make a new instance of the appropriate class and throw that instance. What this code does is create a method for dividing double values that throws an exception if the divisor is zero (0). (Normally, operations involving double values never throw an exception, not even when executing something like 1.0/0.0.)

Throwing Exceptions

However, it is possible for your program to throw an exception explicitly, using the throw statement. The general form of throw is shown here:
throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. Primitive types, such as int or char, as well as non-Throwable classes (such as String and Object), cannot be used as exceptions. There are two ways you can obtain a Throwable object:
  1. using a parameter in a catch clause or
  2. creating one with the new operator.

The flow of execution stops immediately after the throw statement and any subsequent statements are not executed. The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of exception. If it does find a match, control is transferred to that statement. If not, then the next enclosing try statement is inspected, and so on. If no matching catch is found, then the default exception handler halts the program and prints the stack trace.
Here is a sample program that creates and throws an exception. The handler that catches the exception rethrows it to the outer handler.

Throwing Exceptions - Quiz

The following quiz poses questions with respect to throwing exceptions.
Throwing Exceptions - Quiz