I have 5 methods e.g. 1, 2, 3, 4, 5. I am calling method2 from method1, method 3 from method2 and so on. Suppose an exception happens in Method5 and I am handling it in the try-catch block, how will I know this in Method1?
-
is the exception checked ? if it is, do the 5 methods declare it ? if they dont, are you allowed to change the signature of all 5 methods ? is there some reason to catch it in method 5 if you want to handle it in method 1 ? ... which leads me to the main question: who will handle it ? is there some way any of the five methods can correct the error condition? are you supposed to log it and abort? or show the user a helpful message to solve the situation?... – jambriz May 09 '12 at 04:23
4 Answers
You may want to look into exception propogation. This other question describes it fairly well. Essentially, if the exception is not in a try-catch it will bubble up to the callee until it is either at the top of the call stack, or is caught.
-
-
It's been in Java as long as I've been working with it. You may want to check the [documentation](http://docs.oracle.com/javase/tutorial/essential/exceptions/). [1.4.2](http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Exception.html) has the earliest documentation I could find. – Igor May 09 '12 at 04:18
You'll have to set a variable/flag that both method1 and method5 have access to. Something like a field in the same class should work.
private String exceptionHappened = "";
private void method1() {
method(2);
// Here I can check value of exceptionHappened
}
//... methods 2-4
private void method5() {
try {
// ...
} catch (Exception e) {
this.exceptionHappened = "In method 5";
}
}

- 53,220
- 42
- 124
- 197
The exception, if not caught, propagates in the call hierarchy till it reaches the main method. If a method wants to know if there was any exception in the call hierarchy then it should try-catch
block to take the control of the exception flow.

- 17,667
- 4
- 54
- 79
Create a user defined exception and have a property in that class to store the method name. Now in ur case, in method5 , in catch block throw the user defined exception which u created by setting the method name to "methodname" property. Throw that exception till fir method1(or what ever the root method), then based on value in the methodname property, you can confirm which method the exception is thrown.

- 21
- 1