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.

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

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?

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

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)

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.

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?

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)

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.

Inderpreet said:   1 decade ago
Since the catch expresion contains

System.out.println("Exception");

Isn't it that the output should be 'exception' ?

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.


Post your comments here:

Your comments will be displayed after verification.