Java exceptions: myException is never thrown into the body of the corresponding try statement

I understand the idea of ​​this error. But I think I don’t understand how this works in the call stack.

Main.java file:

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, after a few calls (down the call stack), I have Function2, which indicates the requirement "throws myException". Why doesn't the main function (where the error is sent) recognize that I am throwing myException on a line?

Any guidance in which the “hole” in my “exception” is at the core is appreciated.

aitee

+4
source share
2 answers

The hole is that Function2 declares that it throws an exception, but Function1 does not. Java does not make its way through possible call hierarchies, but directly what you declare in throws statements.

Function1 leaves without declaring a throw, probably because myException is a RuntimeException .

+1
source

Your problem is that Function1() does not declare that it is throws myException - it means that there must be two compilation errors: one about the exception that was not caught or declared, and the other about the exception that was not declared.

+1
source

All Articles