Is there any chance of getting multiple exception?

  • Lets see a java example programs which can raise multiple exceptions.


  1. package exceptions;
  2. public class MultipleCatchBlocks {
  3.  
  4.     /**
  5.      * @www.instanceofjava.com
  6.      */
  7.  
  8. public static void main(String[] args) {
  9.         
  10.         
  11.  int x=10;
  12.  int y=0;
  13.  
  14. try{
  15.             
  16.    int i=x/y;
  17.    int a[]=new int[2];
  18.    a[3]=12;
  19.             
  20. } catch(ArithmeticException e){
  21.             e.printStackTrace();
  22. }
  23.  
  24. }
  25.  
  26. }

Output:


  1. java.lang.ArithmeticException: / by zero
        at exceptions.MultipleCatchBlocks.main(MultipleCatchBlocks.java:15)

  •  Lets see second case:


multiple catch blocks in java




try with multiple catch blocks

  • In the 1st program there is a chance of getting two types of exceptions and we kept only one catch block with  ArithmeticException e . 
  • But there will be chance of getting ArrayIndexOutOfBoundsException too. 
  • So we need to keep multiple catch blocks in order to handle all those exceptions
  • Or else we can keep single catch block with super class Exception class object.

 




Multiple catch blocks for single try block:

 

  • One try can have multiple catch blocks 
  • Every try should and must be associated with at least one catch block.( try without catch)
  • Whenever an exception object is identified in try block and if there are multiple catch blocks then the priority for the catch block would be given based on order in which catch blocks are have been defined.
  • Highest priority would be always given to first catch block . If the first catch block can not handle the identified exception object then it considers the immediate next catch block.

Disadvantages of multiple catch blocks:
 
  •  We have to know the names of every corresponding exception class names.
  • We have to understand which statement is generating which exception class object.



Solution: 

  •  Define a single catch block so that it should be able to handle any kind of exceptions identified in the try block.
  • Exception class is the super class for all the exception classes.
  • To the reference of super class object we can assign any sub class object.

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

1 comments for Multiple catch blocks in java example

Select Menu