Exception: – An exception is a condition that is caused by a run time error in the program. When the java interpreter encounters an error such as dividing an integer zero and creates an exception object and throw it.

If the exception object is not caught and handle properly, the interpreter will display and error message and will terminate the program. If we want the program to continue with the execution of the remaining code, then we should try to catch the exception object thrown by the error condition and then display an appropriate message for taking corrective action. This task is known as exception handling.

The purpose of exception handling mechanism is to provide a means to detect and report an “Exceptional circumstance” so that appropriate action exception handling can be taken. The mechanism segment incorporation of a separate error handling code that performs the following task –

  1. Find the problem
  2. Inform that an error has occurred
  3. Receive the error information
  4. Take correction action

The error handling code basically consist of two segments, one to detect error to throw exception and the other catch exception and to take appropriate action. Syntax of the exception handling –

                Statements for an exception
catch(Exception type e)
                Statements for process the exception

The try block can have one or more statement that could generate an exception. If anyone statement generate an exception, the remaining statement in the block are skipped and execution jump to the catch block that is placed next to the try block.

Finally statement: – Java support a statement known as finally statement that can be used to handle an exception that is not caught by the catch statement. The finally block can be used to handle any exception generated within a try block. It may be added immediately after the try block.

When a finally block is defined, this is granted to execute, regardless of whether or not in exception is thrown as a result, we can use it to perform certain housekeeping operation such as closing files and releasing system resources. Syntax of the finally statement is –

                Finally block