J2EEOnline J2EE 






Java Exceptions  «Prev  Next»
Lesson 7Throw your own exception in Java
ObjectiveThrow an exception in Java.
In addition to simply handling Java's exceptions, you can also throw your own exception.
Here's 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 - Quiz
The following quiz poses questions with respect to throwing exceptions.
Throwing Exceptions - Quiz