Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Assertion

 
Girish Nagaraj
Ranch Hand
Posts: 153
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

Have a look at this piece of code.

import java.io.*;

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
Posts: 584
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
bnkiran kumar
Ranch Hand
Posts: 176
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Girish Nagaraj
Ranch Hand
Posts: 153
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic