Chris Kessel
Chris Kessel

Reputation: 5875

Why am I not forced to catch Exception here?

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 :)

Upvotes: 5

Views: 370

Answers (1)

Mario Rossi
Mario Rossi

Reputation: 7799

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.

Upvotes: 8

Related Questions