Tuesday, 24 June 2008

Throw null.

« Dont put a lot in IN. | Main
Eugene posed an interesting question about Alex' blog entry on why the following code does not require main method to throw throwable -
  public class Weird {  
    public static void main(String[] args) {  
      throw null;  
    }  
  }
The fact that it throws a NPE has been discussed on Alex' blog.
But the reason(or my hypothesis) why the compile dos not require you to add a Throwable to throws clause is as follows -
  1. The null reference can always be cast to any reference type.
  2. Checked Exceptions should be declared in the throws clause.
  3. RuntimeExceptions and Descendants are exempt from the above requirement(2)
  4. Rephrasing 2 and 3 as "if the type is not an instance of RuntimeException", which translates to the following code -
    if(!(type instanceof RuntimeException)) {
     //check throws clause for validity
    }else {
     //dont check.
    }
    
    and we can see that 'null' case would go to the else block.
Q.E.D. ? (you decide)
Posted by sid at 12:27 PM in Thoughts on Java/J2EE

 

[Trackback URL for this entry]

Your comment:

(not displayed)
 
 
 

Live Comment Preview:

 
« June »
SunMonTueWedThuFriSat
1234567
891011121314
15161718192021
22232425262728
2930