Java Try Catch Finally

Advertisements

Java Exception Handling - Try Catch Finally

An exception is a situation, which occurred by the run-time error. In other words, an exception is a run-time error. An exception may result in loss of data or an abnormal execution of program.

Exception handling is a mechanism that allows you to take appropriate action to avoid run-time errors.

Java provides five keywords to support exception handling.

  • Try : The try block contain statements which may generate exceptions.
  • Catch :The catch block defines the action to be taken, when an exception occur.
  • Throw : When an exception occur in try block, it is thrown to the catch block using throw keyword.
  • Throws : Throws keyword is used in situation, when we need a method to throw an exception.
  • Finally : If exception occur or not, finally block will always execute.

The general form of try-catch block in Java.




When a run-time error occur within a method, method creates an object of corresponding exception class and pass it to run-time system. The object is called an exception object. The exception object includes information about the type of error, exception class name the state of program when error occur. Creating an exception object and handing it to the run-time system is called throwing an exception. When a method throws an exception object, run-time system attempts to find the corresponding catch block to handle the exception. This block is called exception handler. When run-time system finds the corresponding exception handler, it is said to be catch an exception. If no corresponding exception handler found, run-time error will occur or we can say exception will occur.

Example of simple try catch block in java


//ExceptionDemo.java

    class ExceptionDemo
    {
        public static void main(String[] args)
        {

        int a=45,b=0,rs;

        try
        {
            rs = a/b;       // Statement 1
            System.out.print("\n\tThe result is : " + rs);
        }
        catch(ArithmeticException Ex)
        {
            System.out.print("\n\tError : " + Ex);
        }

        System.out.print("\n\n\tEnd of program");

        }
    }

    Output :
                Error : java.lang.ArithmeticException: / by zero

                End of program

In the above example, statement 1 will generate run-time error b'coz we are trying to divide a number by zero. Method will create an exception object of ArithmeticException class and throw it to the catch block. Now, the catch block will get execute and display the exception details.

Java Multiple Catch Statements

A single try statement can have multiple catch statements. Execution of particular catch block depends on the type of exception object thrown by the method. If the exception object is of ArithmeticException class, catch block with ArithmeticException will get execute. If no corresponding catch block found, run-time error will occur.

Example of multiple catch statements in java


//MultipleCatchDemo.java

    class MultipleCatchDemo
    {
        public static void main(String[] args)
        {
            int a=45,b=0,rs;
            int[] arr = new int[5];

            try
            {
                arr[45] = 78;           // Statement 1

                rs = a / b;             // Statement 2
                System.out.print("\n\tThe result is : " + rs);
            }
            catch(ArithmeticException Ex)
            {
                System.out.print("\n\tError : " + Ex.getMessage());
            }
            catch(ArrayIndexOutOfBoundsException Ex)
            {
                System.out.print("\n\tError : " + Ex.getMessage());
            }

            System.out.print("\n\tEnd of program.");
        }
    }

   Output :

              Error : 45
              End of program.

In the above example, both statements 1 and 2 have run-time errors but only statement 1 will generate an ArrayIndexOutOfBoundsException and the corresponding catch block will execute b'coz once an exception occur in try block, rest of the statements in try block will be ignored.

Java Catch All Exceptions

The above example will caught only two types of exceptions that are ArithmeticException and ArrayIndexOutOfBoundsException. If any other exception occur, no catch block will get execute and abnormal program termination will occur. To avoid this, We can use the catch statement with Exception's class object as parameter, so that it can handle all types of exceptions b'coz Exception class is the base class of all the run-time exception classes.

Example of catch all exceptions in java


//CatchAllExceptionsDemo.java

    class CatchAllExceptionsDemo
    {
        public static void main(String[] args)
        {
            int a=45,b=0,rs;
            int[] arr = new int[5];

            try
            {
                arr[45] = 78;           // Statement 1

                rs = a / b;             // Statement 2
                System.out.print("\n\tThe result is : " + rs);
            }
            catch(Exception Ex)
            {
                System.out.print("\n\tError : " + Ex.getMessage());
            }

            System.out.print("\n\tEnd of program.");
        }
    }

   Output :

              Error : 45
              End of program.

Java Rethrow Exceptions

Rethrowing exception is possible, where we have an inner and outer try-catch statements (Nested try-catch). An exception to be thrown from inner catch block to outer catch block is called rethrowing exception.

Syntax of rethrowing exception in java




Example of rethrowing exception in java


//RethrowingExceptionDemo.java

    class RethrowingExceptionDemo
    {
        public static void main(String[] args)
        {
            int a=45,b=0,rs;
            int[] arr = new int[5];

            try
            {

			    try
			    {

			        arr[45] = 78;

			    }
			    catch(ArrayIndexOutOfBoundsException Ex)
			    {
				    rs = a / b;
				    System.out.print("\n\tThe result is : " + rs);
			    }

            }
            catch(ArithmeticException Ex)
            {
                System.out.print("\n\tError : " + Ex.getMessage());
            }

            System.out.print("\n\tEnd of program.");
        }
    }

    Output:
                Error : / by zero
                End of program.

Advertisement