Vous êtes sur la page 1sur 3

Exception handling -

An exception is an abnormal situation occurring during the execution of the program which
terminates the program abruptly.

When an exception is encountered JVM follows:

1) Identifies the exception


2) Create an object off that exception class
3) Put all the detail of the exception in that object
4) Checks whether that that exception is handled
a) Check in that function. If it is handled, handler is executed
b) If it is not present, JVM goes stock prior & checks for handles.
c) If no handler is found, JVM executes default handler (terminates the program).

Types of exceptions:

1) DivideByZeroException
2) NumberFormatException
3) InputMismatchException
4) IOException
5) ArrayIndexOutOfBoundsException
6) StringIndexOutOfBoundsException
7) NullPointerException

There are two ways to handle an exception:

1) Try, Catch & Finally


2) Throws

Try block:

The statements which are prone to an exception are written in the try block, whenever an exception
occurs in the try block the catch block is executed.

Catch Block:

Catch block is used to handle the exception which occurred in the try block. It follows the try block
and defines the plan of action to be executed when an exception occurs.

Finally Block:

It is written after the try and the catch block. Finally block is executed irrespective of whether the
exception occurs or not.

A try block can be followed by either a catch block or a finally block.

Checked Exception:

The compiler checks whether the exception is handled or not.

eg – IOException, FileNotFoundException.

Unchecked Exception:
An Exception which may or may not be handled & is not checked by compiler.

To handled Checked Try – Catch OR Throws.

Throws:

Is a keyword which is used to handle an exception by writing throws in the signature of the function

We specify that the calling function will be handling the exception. In case, if main throws the
exception it will be given to the JVM for its default handler.

Keyword throw:

Throw is used to force an exception. That is an exception can be created and thrown by the user.

if(n<0)

throw new InputMismatchExcepiton();

else if(n>0)

throw new ArrayIndexOutOfBoundsException();

Instance Functions of class Exception:

1) getMessage() – Prints the message associated with the particular exception.


2) printStackTrace() – It prints the trace of where the exception occurred in the present
function and the calling functions.

Vous aimerez peut-être aussi