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

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?

Bhaskara said:   1 decade ago
When ever we have try with multiple catch blocks, the order of the catch block is very important in this case, and it should be from child to parent, otherwise then we will get compilation fails saying "the exception is already been caught".

Pop said:   1 decade ago
Can we use more than one catch blocks with one try block ? if not than please tell me the reason.

Tony said:   1 decade ago
When Exception class is caught, why "Exception" is not printed.

Hema said:   1 decade ago
Since all kinds of exceptions are caught by Exception class the output should be "exception" isnt it? Why would compilation fail?

Dheeraj said:   1 decade ago
Some of you said that Exception is the super top class but it is wrong, all the Exceptions has only one base class i.e. Throwable class.

Tejas said:   1 decade ago
After running code:

Exception in thread "main" java.lang.RuntimeException:

Uncompilable source code - exception java.lang.ArithmeticException has already been caught
at Test.main(Test.java:12)
Java Result: 1

Vijeesh v r said:   1 decade ago
If we give finally statement and use Arithmetic ;what will be the output?

Sanjeev said:   1 decade ago
So simply speaking,

Whenever try with multiple catch blocks, the order of catch blocks is very important and it should be from child to parent, otherwise we will get an compilation error saying "Exception already been caught".

Asad said:   1 decade ago
Unreachable catch block for ArithmeticException. It is already handled by the catch block for Exception.

So remove catch and replace throws. Compilation error is correct option


Post your comments here:

Your comments will be displayed after verification.