Let's say there are three consecutive function calls in one try
block and all of them throw the same type of exception. How can i figure out which function call threw the caught exception when handling it?
views:
174answers:
5You can put a try-catch block around every single method call.
Or you take a look at the exception stack trace. Their is described which line of code throwed the exception.
getStackTrace()[0].getMethodName()
EDIT:
- old method: have three try/catch blocks
- new method (since 1.4): Throwable.getStackTrace()[0]
like this:
try {
function1();
} catch (Exception e){
// function1 error
}
try {
function2();
} catch (Exception e){
// function2 error
}
try {
function3();
} catch (Exception e){
// function3 error
}
So I'm guessing that something about your code makes the obvious solutions tricky, perhaps the method call sites are a level or two down, or not at the same level? What exactly prevents you from just keeping a counter?
In any case, you need to either count invocations, use multiple try blocks, or do that and define your own exception which contains the missing information (and the old exception, because it's a subclass) and then rethrow it.
Perhaps you could subclass the object with the exception-throwing method, in order to wrap the method call and implement the counter?
I think introspecting the stack trace to do error handling will hurt you very badly later. If you need separate actions for separate lines, then have them in individual try-catch blocks.
You may also just want to have a simple variable keeping state, so you can check on the value, to determine how far you got. I think that will work much better.
int state = 0;
try {
step1();
state = 1;
step2();
state = 2;
....
} catch (Exception e) {
if (state == 2) ....
}
Edit: Downvoters, please notice I started saying this is a bad idea ;-)