Java Programming - Exceptions - Discussion

Discussion Forum : Exceptions - Finding the output (Q.No. 2)
2.
What will be the output of the program?
try 
{ 
    int x = 0; 
    int y = 5 / x; 
} 
catch (Exception e) 
{
    System.out.println("Exception"); 
} 
catch (ArithmeticException ae) 
{
    System.out.println(" Arithmetic Exception"); 
} 
System.out.println("finished");
finished
Exception
Compilation fails.
Arithmetic Exception
Answer: Option
Explanation:

Compilation fails because ArithmeticException has already been caught. ArithmeticException is a subclass of java.lang.Exception, by time the ArithmeticException has been specified it has already been caught by the Exception class.

If ArithmeticException appears before Exception, then the file will compile. When catching exceptions the more specific exceptions must be listed before the more general (the subclasses must be caught before the superclasses).

Discussion:
28 comments Page 1 of 3.

Veera said:   4 years ago
If we get any type of exception, Exception block will catch that, then why we need to take different catch blocks like ArithmeticException, ArrayIndexOutOfBoundsException etc.
(1)

Omkar said:   6 years ago
Hi, why we do use the Exception e in the catch block? what is the exact meaning of try and catch block & when it needs in a program?
(1)

Choti said:   6 years ago
If we change the order catch block means if we write 2nd catch block at a 1st place then the o/p:

Arithmetic Exception.
Finished.

Coders_Sutra said:   8 years ago
Yes, right @Vinod Kumar.

As the 5/0 was already lead to an exception just the compiler now is finding the Arithmetic exception declaration in the catch block or the finally block in the program after try block therefore if you write the super class ""Exception e"" before the subclass this is not the concept.

N.saikrishna said:   9 years ago
The order is important.

First, we have to write child class and next parent class other wise there will be compile time error.

SRINIVAS said:   9 years ago
It will check whether the most specific one is next or not and has nothing to do with compilation.

Shruti said:   9 years ago
After ending of try block braces is not there so compilation failed.

Anup kumar said:   9 years ago
Here, the try block is of arithmetic exception type. So, a catch block arithmetic exception should come before the catch block exception ae.

That's why compilation fails.

Akash said:   9 years ago
Once it find an error which is caught by 1st catch block then automatically it will display compilation error because once compilation error occurred then it quit by displaying error msg so the 2nd block will not be executed.

Hritika said:   10 years ago
What will the output if Arithmetic Exception class is handled first & if Exception class is found later, then also compiler has to read same thing again then why not compilation error is printed?


Post your comments here:

Your comments will be displayed after verification.