4

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,

aitee
  • 45
  • 1
  • 1
  • 4
  • if myException a runtime exception? if you need to have Function2 throw myException, Function1 should also throw it. – hvgotcodes Nov 30 '10 at 19:30
  • What's the relation between the classes Main and File2 ? (which one does inherit from which one ?) – Andre Holzner Nov 30 '10 at 19:31
  • This doesn't relate directly to your question, but I strongly suggest adhering to the naming conventions: Methods like `Function1` and `Function2` should start with a lowercase letter, and classes like `myException` should start with a capital. Conventions allow you and other programmers to better understand each others' code. – Carl Smotricz Nov 30 '10 at 19:35
  • @Carl Smotricz, My bad. I am not familiar with java conventions. I will keep this in mind from now on. Do you know of a reference for more java naming conventions, or java conventions in general? – aitee Nov 30 '10 at 19:53
  • see here, especially section 9 : http://www.oracle.com/technetwork/java/codeconvtoc-136057.html – Michael Borgwardt Nov 30 '10 at 20:22

2 Answers2

1

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.

Carl Smotricz
  • 66,391
  • 18
  • 125
  • 167
  • So your saying that I need to declare a chain of throws myException all the way up? – aitee Nov 30 '10 at 19:38
  • Well, that fixed it... Thank you so much. So the path (down the callstack) from the handler to the throw must have the requirement that each function along the way can "throw" (or pass the throw) all the way up to the handler? – aitee Nov 30 '10 at 19:47
1

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.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720