Java Exceptions: exception myException is never thrown in body of corresponding try statement

StackOverflow https://stackoverflow.com/questions/4317643

문제

I understand the idea of this error. But I guess I don't understand how this works down the call stack.

File Main.java:

public static void main(String[] args) {
    try {
         Function1();
      } catch (myException e) {
      System.out.println(e.getMessage());
    }
}
public static void Function1() {
    Function2();
}

Function2 exists in another file:

File2.java

public void Function2() throws myException {
     ....
}

So through several calls (down the call stack) I have Function2 which specifies the requirement "throws myException". How come the main function (where the error is being directed at) doesn't recognize that I throw myException down the line?

Any guidance in where the 'hole' in my "exception knowledge" lies would be greatly appreciated.

aitee,

도움이 되었습니까?

해결책

The hole is that Function2 declares that it throws the exception, but Function1 does not. Java doesn't dig its way through possible call hierarchies, but goes directly by what you declare in throws statements.

Function1 gets away with not declaring the throw probably because myException is a RuntimeException.

다른 팁

Your problem is that Function1() does not declare that it throws myException - which means that there should be 2 compile errors: one about the exception not being caught or declared, and one about catching the exception that is not declared.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top