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 3 of 3.

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.

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

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

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.

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.

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.

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)

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)


Post your comments here:

Your comments will be displayed after verification.