简体   繁体   中英

Why i can`t throw Exception(checked) in a method that is invoked in a try catch statement?

 public class simple {
    public static void main(String[] args) {
        try {
            System.out.print("hello ");
            throwit();
        } catch (Exception re) {
            System.out.print("caught ");
        }
    }

    public static void throwit(){  // line number 11
        throw new Exception();  // line number 12
    }
   }

why does it give me a compile error in line number 12. If i use throws Exception for line number 11 then it work fine. If i throw subclass of Exception(in line number 12) then it work properly... why so?...

I want to know actually what happen in back side(how does compiler shows error for this)?

You have a method there which is throwing a checked exception, but its method signature doesn't specify that it is able to do that. All checked exceptions have to be declared in the method signature, and explicitly handled by try/catch blocks or by rethrowing; that's what the definition of a checked exception is. :)

This line:

public static void throwit()

should be

public static void throwit() throws Exception

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