Meaningless Drivel is fun!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Assertion 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" Watch "Assertion" New topic


Girish Nagaraj
Ranch Hand

Joined: Apr 19, 2006
Posts: 153
Hi All,

Have a look at this piece of code.


class AssertionTest {

int a = 2;

public void func() {

assert (a < 0): "a is positive";

public class Test12 {

public static void main(String[] args) {

try {

(new AssertionTest()).func();

} catch (Exception e) { // (1)

System.out.println("Exception caught");

} catch (AssertionError e) {

System.out.println("AssertionError caught");

Why do we get output "AssertionError caught".Why not "Exception caught".

Also it doesnot give compile time error even though "AssertionError" is caught after "Exception".(more broader)???
Edisandro Bessa
Ranch Hand

Joined: Jan 19, 2006
Posts: 584
Hi Girish,

First of all. Welcome to JavaRanch.

Both Error and Exception classes are siblings in the inheritance tree. Both are Throwable's childs. So, as AssertionError is a subclass of Error, the expected result can never be "Exception caught".

Think about that : If AssertionError were a subclass of Exception, just a supposition, you would get a compile error because the most specific class have to appear first in the catch clause followed by its superclasses.

Please let me know if I can do anything else to help you with.

Best Regards.
[ April 20, 2006: Message edited by: Edisandro Bessa ]

"If someone asks you to do something you don't know how to, don't tell I don't know, tell I can learn instead." - Myself
bnkiran kumar
Ranch Hand

Joined: Mar 02, 2006
Posts: 176
The simple reason why it is not getting caught is that, Exception not superclass of AssertionError,
if it were ,then your code might have not executed because compiler might have objected that catch(AssertionError e) is unreachable, as it was not happened ,you got the evidence, i think

what do you say.

Kiran Kumar.
Girish Nagaraj
Ranch Hand

Joined: Apr 19, 2006
Posts: 153
Hey thanks Edisandro and kiran.

I checked Exception hierarchy chart you ppl are right.

Exception and Error are siblings of Throwable class and Assertion is subclass of Error.
I agree. Here's the link:
subject: Assertion
It's not a secret anymore!