Customized Exception handling by try-catch

Customized Exception handling by try-catch

  • It is highly recommended to handle exceptions.
  • The code which may raise an exception is call risky code and we have to define that code inside try block and corresponding handling code we have to define inside catch block.
 try
 {
     // Risky code
 } catch ( Exception e ) {
    // Handling code
 }
 
with and without try catch


Control flow in try-catch

Controll flow in try catch 

 Note:

  1. Within the try block if any where exception raised then rest of the try block would not be executed even though we handle that exception.
  2. Hence within the try block we have to take only risky code and length of try block should be as less as possible. 
  3. In addition to try block there may be chance of raising an exception inside catch/finally block.
  4. If any statement which is not part of try-block and raised an exception then it is always abnormal termination.
 

Method to print Exception information 

Exception information methods 

 

 Ex:

Exception handling example

Note:

Internally default exception handler will use printStackTrace() method to print exception information to console.

Try with multiple catch block

The way of handling an exception is varied from exception to exception. Hence for every exception type it is highly recommended to take separate catch block. Means try with multiple catch blocks is always possible and recommended to use.
 
     Try with multiple catch 
  • If try with multiple block present then the order of catch block is very important. We have to take child first and then parent. Otherwise we will get compile time error, saying

try with multiple catch in java 

Ex:

Example of multiple catch in java 
 
  • We cannot declare 2 catch blocks for the same exception otherwise we will get compile time exception.
Multiple catch with try 
 
RAKESH RAKA

I am Rakesh Raka, senior software engineer (JAVA) in Sopra Steria.

Post a Comment (0)
Previous Post Next Post