File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Assertion Exception handling Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Assertion Exception handling" Watch "Assertion Exception handling" New topic

Assertion Exception handling

prashanth kumar
Ranch Hand

Joined: Mar 22, 2004
Posts: 162
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

Why is that?

Many Thanks

SCJP1.5(86%)<br />SCWCD1.4(95%)<br />SCBCD1.3(92%)<br />IBM 252
Henry Wong

Joined: Sep 28, 2004
Posts: 20534

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.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
prashanth kumar
Ranch Hand

Joined: Mar 22, 2004
Posts: 162
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.

I tested this and it works.

Thanks Again
Ramu Malur S R

Joined: Oct 17, 2006
Posts: 26
Hi Prashanth,

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.

- Ramu

"Excellency is rarely found, more rarely valued"
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
What can you catch when try block does not throw exception?
I agree. Here's the link:
subject: Assertion Exception handling
It's not a secret anymore!