简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM