Is there any chance of getting multiple exception?
Output:
Disadvantages of multiple catch blocks:
Solution:
- Lets see a java example programs which can raise multiple exceptions.
- package exceptions;
- public class MultipleCatchBlocks {
- /**
- * @www.instanceofjava.com
- */
- public static void main(String[] args) {
- int x=10;
- int y=0;
- try{
- int i=x/y;
- int a[]=new int[2];
- a[3]=12;
- } catch(ArithmeticException e){
- e.printStackTrace();
- }
- }
- }
Output:
- java.lang.ArithmeticException: / by zero
at exceptions.MultipleCatchBlocks.main(MultipleCatchBlocks.java:15)
- Lets see second case:
- 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.
sir can u upload hibernate
ReplyDelete