Course Content‎ > ‎Session 10‎ > ‎

try-catch-finally

Java has a mechanism for handling exceptions, so that the program can continue to run as if nothing had happened. This mechanism is based around two statements: try and catch.

try-catch 

This statement is placed before a block of code which the programmer suspects might generate an exception. The catch statement comes straight after the try block and specifies what type of exception is being caught, a block of instructions after the catch statement are executed, if the generated exception matches the one in the catch. There can be multiple catch statements, after a try block all with the different exceptions. For example, the following program has two classes, the constructor for twoExc takes two int parameters divides the first by the second and accesses an array using the result as the index.

    class testException
    {      
        public static void main (String args[])
        {
            exceptionEg first = new exceptionEg(10, 0);
            exceptionEg second = new exceptionEg(110, 10);
        }
    }
    
    class exceptionEg
    {
        int array[] = new int[10];
        int index;
        
        divideNumbers (int a, int b)
        {
            try 
            {  
                // possible divide by 0
                index = a / b; 
                
                // possible array out of bounds
                array [index]  = 0; 
            }
            catch (ArithmeticException e)
            {
                System.out.println ("Divide by 0");
            }
            catch (ArrayIndexOutOfBoundsException e) 
            {
                System.out.println ("Array Index Out of Bounds");
            }
        }
    }  

The call stack

It is possible to allow an exception to move backwards through the call-stack, until a catch clause is found, which is the the same type as the exception. If the main method calls print method and print in turn calls another method called display; if an exception occurs in display, then a check will be made to see if there is a catch for the exception, if not then the next method in the call-stack (print) will be made, then the next (main), if the exception is not handled by the last method on the call-stack, then a runtime error occurs and the program stops running.  

throw

It is possible to actually throw an exception from within the program code, using the keyword throw. This is useful if an exception is caught in the method and the calling method also needs to be informed of the exception. For example,

    class testThrow
    {
        static void called_method ()
        {
            int a = 0;
            int b;
            try 
            {  
                // exception
                b = 10 / a; 
            }
            catch (ArithmeticException e) 
            {
                System.out.println ("divide by 0: in called_method");
                throw e; // throw the exception
            }
        }
        public static void main (String args[])
        {
            try 
            {
                called_method ();
            }
            catch (ArithmeticException e) 
            {
                System.out.println ("divide by zero: main");
            }
        }
    }

It is also possible to create an instance of an exception using the new operator.

    class newExc
    {
        public static void main (String args[])
        {
            ArithmeticException newExc = new ArithmeticException ();
            try 
            {
                throw newExc;
            }
            catch (ArithmeticException e) 
            {
                System.out.println ("caught the generated exception");
            }
        }
    }  

finally

Usually when an exception is thrown, the code immediately stops executing and goes looking for a catch block to match the exception. It is sometimes useful to have a piece of code, which runs no matter what exceptions have been generated and handled. This is known as the finally block. Here is an example to illustrate the above:

    class finallyTest
    {
        public static void main (String args[])
        {
            int a = 0;
            try 
            {  
                // causes an exception
                System.out.println (1 / a);
            }
            catch (ArithmeticException e)
            {
                System.out.println ("Divide by 0");
            }
            finally 
            {
                System.out.println ("Finally block");
            }
        }
    }

Comments