prev next prev next
  Course navigation
  Lesson 7 Throw your own exception in Java
 
Objective
Throw 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:
 
active directory, oracle, pmp

soa testing, php, surveillance, QOS in VoIP
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
Here's a quiz on throwing exceptions.
Throwing Exceptions Quiz
  Course navigation