The term exception is shorthand for the phrase "exceptional event." Definition : An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions.

 When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception. After a method throws an exception, the runtime system attempts to find something to handle it.

 Some of the predefined exception classes are :

 ArithmeticException, ArrayIndexOutOfBoundException, IOException etc.



The try Block : The first step in constructing an exception handler is to enclose the code that might throw an exception within a try block. In general, a try block looks like the following. 

try { code } catch and finally blocks . . . 

The segment in the example labeled code contains one or more legal lines of code that could throw an exception. A catch Block : A catch block defined by the keyword catch ―catches‖ the exception ―thrown‖ by the try block and handles it appropriately.The catch block is added immediately after the try block.

The general form is : ………………….. …………………… try { statement; } catch(Exception type e) { statement; } ……………….. ………………


Using Finally Statement : Java supports another statement known as finally statement that can be used to handle an exception that is not caught by any of the previous catch statements. Finally block can be used to handle any exception generated within a try block. It may be immediately after the try block or after the last catch block. When a finally block is defined, this is guaranteed to execute, regardless of whether or not in exception is thrown. Throwing our own Exceptions : There may be times when we would like to throw our own exceptions. We can do this by using the keyword throw as follows : throw new Throwable_subclass; e.g. throw new Arithmetic Exception();
Designed By Blogger Templates | Templatelib & Distributed By Blogspot Templates