Try with Multiple Catch blocks

This “Try with Multiple Catch blocks” page explains clearly when we define more than one catch block for a single try block in exception handling process in Java.

core-java-online-training-3

Try with Multi Catch:

  • Try block contains many instructions.
  • Each instruction can raises an Exception.
  • try with multiple catch blocks used to handle different exceptions occurred in different instructions of try block.
  • We use try with multiple catch blocks when one task depends on more than one step of process and in each step there is a chance of getting exception.
  • Following examples explain clearly.

Try with Multiple Catch blocks

 

Syntax :

try
{
Chance to get Exception1
…..
…..
Chance to get Exception2
}
catch(Exception1 <var>)
{
Exception1 handling logic…
}
catch(Exception2 <var>)
{
Exception2 handling logic…
}

 

Task : Open File –> Write info –> Send in Network –> End

 

Note the followings…

  • If Exception has risen in the try block, control terminates the execution of followed statements in try-block and executes the catch block.
  • After execution of catch block, control will never back to try.
  • If no exception in try block, no catch block will be executed.
  • It is possible to handle one Exception at a time among multiple catch blocks.

 

Example Code to describe Try with Multi catch:

core-java-online-training-3

Share this