This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Hello All, How can following code compile? Iam asking this because,this code block is trying to catch an Exception which is never thrown[AssertionError is NOT a child of Exception].But code still compiles
The Exception class is also the base class for the RuntimeException class. The compiler is allowing the Exception here because it can't tell if it "is trying to catch an Exception which is never thrown" -- it could be an unchecked exception that is caught.
Thanks for the clarification. This means that a called method[even if it doesnt throw any chcecked exceptions] can always be there in try-catch block of calling method with "Exception" catch, since RunTimeException is a subclass of Exception. Ex:
Including any code in the try block does not mean that the code should throw an exception.
Compiler only cares about checked Exceptions and since AssertionError is a runtime Error(not an exception, it does not even come under Exception heirarchy ), the compilation proceeds even if you don't deal with it.
Moreover it is not a good practice to handle Assertion errors(As they can be disabled when the code compiles or runs), it is meant to use only during development not during deployment.