1

Here is my program.

try {
    int a = 1/0;
}
catch(Exception e) {
    system.out.println("Exception block"+e);
}
catch(ArithmeticException e) {
    system.out.println("Inside ArithmeticException block");
}
finally {
    system.out.println("Inside Finally block");
}

In the above program i have two catch blocks and one finally block.

Which catch block will execute? Because I define the parent catch block first. So it leads to an error? Can any one help me?

I assumed that "ArithmeticException and Finally block will be executed"

Gabriel Rainha
  • 1,713
  • 1
  • 21
  • 34
Guru
  • 21
  • 5

2 Answers2

2

Catching Exception class will not give any error. However, it is not recommended.

In this case, Exception catch block will execute first and then finally block will execute.

If you want that your ArithmeticException block should execute, put this block before Exception catch block.

Update code -

    try{
        int a = 1/0;
    }        
    catch(ArithmeticException e){
        System.out.println("Inside ArithmeticException block");
    }
    catch(Exception e) {
        System.out.println("Exception block"+e);
    }
    finally{
        System.out.println("Inside Finally block");
    }
Vikas Sachdeva
  • 5,633
  • 2
  • 17
  • 26
0

Catching Exception class will not give any error.

In this case, Exception catch block will execute first and then finally block will execute.

If you want that your ArithmeticException block should execute, put this block before Exception catch block.

Here is Updated code

 try {
    int a = 1/0;
}
catch(Exception e) {
    System.out.println("Exception block"+e);
}
finally {
    System.out.println("Inside Finally block");
}
}