Java

TOPIC i05 – ERROR HANDLING 2

 

 

LESSON NOTE

 

 

INTRO

 

In this lesson, we will learn how to create our own type of Exception and use it in a Java program.

 

OUR OWN CLASS

 

To create our own Exception type, we can simply create our own class that extends Exception. We can of course provide more functionality if we wanted to but for our example, we will keep it basic.

 

EXAMPLE

                                                     

In this example, we will create an exception that occurs when we try to divide a number by zero.  We aren’t adding any new functionality here.

 

public class DivideByZeroException extends Exception

{

   public DivideByZeroException(String m)

   {

        super(m);

   }

}

 

THROWING THE EXCEPTION

 

We can now create a method that will throw our exception.  To do this, we will make use of the throw keyword inside the method block where the exception occurs (or would occur).  Of course, that method now throws the exception (in its method prototype).

 

EXAMPLE

 

The method below divides top by bottom. If bottom is equal to zero, it throws the DivideByZeroException.

 

public static double divide(double top, double bottom) throws DivideByZeroException

{

   if (bottom==0)

   {

         throw new DivideByZeroException("Can't divide by zero.");

   }

   else

   {

         return top/bottom;

   }

}

 

HANDLING THE EXCEPTION

 

We now need to handle our exception.  We do this using the approaches from the previous lesson.

 

EXAMPLE

 

In the main method below, we use a try/catch structure to handle our exception.  Notice that e.getMessage() returns the message that was provide when the exception was created.

 

Note that this main method would be in the same class as the divide method.

 

   public static void main(String[] args)

   {

         try

         {

            double answer = divide(10,0);

         }

         catch(DivideByZeroException e)

         {

               System.out.println(e.getMessage());

         }

   }