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.

Nikhil said:   1 decade ago
I think Inderpreet is correct. If it can't catch exception then what is use of try catch block. It is supposed to catch exception.

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.

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.

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

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

GATTI said:   1 decade ago
Exception class is super class so it never reach the next exception.

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


Post your comments here:

Your comments will be displayed after verification.