Java Exception Handling Machanism

Exception Definition

Exceptions are generated when a recognized an error condition during the execution of a program. Java includes a system for running exceptions, by tracking the potential for each method to throw specific exceptions.

An exception is an event, which occurs during the execution of the proram, that an interrupt the normal flow of the program's instruction. In other words, Exceptions are generated when a recognized condition, usually an error condition, arises during the execution of a method.

Exception Handling Mechanism

The exception handling mechanism performs the following tasks:

A try block can be written and, if problems occur during its execution, control proceeds to the apporopriate catch block.

When a catch block completes execution, control passes to the statement in the finally block.

Using try and catch block

The try statement contains a block of statements. A try block can be written and if problems occur during its excetion, control proceeds to the appropriate catch block.

The general form is:

//statement for monitoring the errors

Catching Exceptions:

Every try block is associated with a corresponding catch block. A catch block must be written after the try block. Each catch block handles the type of exception indicated by its argument. The arument to the catch block is an object of the class Exception.

Simplest form of the catching an exception is as follows:

//statement for monitoring the errrs
catch(exceptiontype excepobj)
  //exception-handling block.

The following program includes try block and catch clause which processes the ArithmeticException generated by the division -by -zero error.

Example 1:

Output :

Exception caught in Catch block
Outside try-catch clause

Example 2:

Output :

You should not divide a number by zero
I'm out of try-catch block in Java.