Java – Try and catch

Java – Try and catch 2017-08-09T13:08:39+00:00

Java Try and catch with example :

We have already seen introduction about try and catch block in java exception handling.

Now here is the some examples of try and catch block.

EX :


Output :
Divide by zero
y = 1
Note that program did not stop at the point of exceptional condition.It catches the error condition, prints the error message, and continues the execution, as if nothing has happened.
If we run same program without try catch block we will not gate the y value in output. It displays the following message and stops without executing further statements.
Exception in thread “main” java.lang.ArithmeticException: / by zero
at Thrw_Excp.TC_Demo.main(
Here we write ArithmaticException in catch block because it caused by math errors such as divide by zero.
Now how to display description of an exception ?
You can display the description of thrown object by using it in a println() statement by simply passing the exception as an argument. For example;

catch (ArithmeticException e)


system.out.pritnln(“Exception:” +e);


Multiple catch blocks :

?It is possible to have multiple catch blocks in our program.

EX :


Output :
Array index error
y = 2
Note that array element a[2] does not exist. Therefore the index 2 is outside the array boundry.
When exception in try block is generated, the java treats the multiple catch statements like cases in switch statement.
The first statement whose parameter matches with the exception object will be executed, and the remaining statements will be skipped.
When you are using multiple catch blocks, it is important to remember that exception subclasses must come before any of their superclasses.
This is because a catch statement that uses a superclass will catch exceptions of that type plus any of its subclasses.
Thus, a subclass will never be reached if it comes after its superclass. And it will result into syntax error.


// Catching super exception before sub

EX :


Output :
If you try to compile this program, you will receive an error message because the exception has already been caught in first catch block.
Since ArithmeticException is a subclass of Exception, the first catch block will handle all exception based errors,
including ArithmeticException. This means that the second catch statement will never execute.
To fix the problem, revere the order of the catch statement.

Nested try statements :

The try statement can be nested.

That is, a try statement can be inside a block of another try.

Each time a try statement is entered, its corresponding catch block has to entered.

The catch statements are operated from corresponding statement blocks defined by try.

EX :


Output :
This is outer catch

Prev Next