Normally, the compiler guards against catch blocks that can never be entered. But there (apparently) comes a point where that's just not practical.
It's virtually impossible for the compiler to predict what type of code might throw any type of Exception (including RuntimeException). So basically, the compiler will "look the other way" and let a catch(Exception) block pass, even if the associated try block is empty.
On the other hand, your own class, MyException, is much more specific, so it's much more reasonable for the compiler to check for code that might throw an instance of MyException.
i dont think the code will even compile. but if you catch MyException before Exception it compiles and prints catch 2 End
following is the updated code
but if you catch Exception before MyException results in a compilation error saying exception block Unreachable since the exception is already caught by a super class. [ April 08, 2005: Message edited by: Rahul Bhosale ]
posted 14 years ago
Assuming that the line "throws new MyException" is corrected, line (1) can be considered an unreachable statement.
A catch block C is reachable iff both of the following are true:
Some expression or throw statement in the try block is reachable and can throw an exception whose type is assignable to the parameter of the catch clause C. (An expression is considered reachable iff the innermost statement containing it is reachable.)
There is no earlier catch block A in the try statement such that the type of C's parameter is the same as or a subclass of the type of A's parameter.
Since the parameter of the first catch block catches Exception and its subclasses, there's no chance for the second catch block to catch MyException.