Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I not forced to catch Exception here?

Tags:

java

Ran across something that's got me puzzled. Why am I not forced to declare "throws Exception" in the method signature here?

  public static void main(String[] args) {
        try
        {
            System.out.println("foo");
            // throw new Exception();
        }
        catch ( Exception e )
        {
            throw e;
        }
    }

Now, if I enable the commented out line, it does force me to declare it which is what I'd expect. I suppose this qualifies more in the Java puzzle category and it's really bugging me that I can't figure it out :)

like image 670
Chris Kessel Avatar asked Aug 30 '13 21:08

Chris Kessel


1 Answers

The compiler is doing data flow analysis and realizing that the only exceptions that can be thrown in that segment are unchecked. So, what you re-throw is an unchecked exception which does not require declaration.

like image 141
Mario Rossi Avatar answered Oct 13 '22 19:10

Mario Rossi