How to determine which function call selected a specific exception in a try block?

Suppose that in a single try block there are three consecutive function calls, and all of them raise the same type of exception. How can I find out which function call caused an exception caught while processing it?

+4
source share
5 answers

You can place a try-catch block around each method call.

Or you look at the exception stack trace. They describe which line of code threw the exception.

 getStackTrace()[0].getMethodName() 

EDIT:

Throwable

StacktraceElement

+10
source

like this:

 try { function1(); } catch (Exception e){ // function1 error } try { function2(); } catch (Exception e){ // function2 error } try { function3(); } catch (Exception e){ // function3 error } 
+2
source
+1
source

So, I assume that something about your code makes obvious decisions difficult, maybe sites with method calls are levels or two down or not at the same level? What exactly prevents you from just holding the counter?

In any case, you need to either count the calls, or use several try blocks, or do it, and define your own exception that contains the missing information (and the old exception, because it's a subclass), and then change it.

Perhaps you could subclass the object using the exception method to wrap the method call and implement a counter?

+1
source

I think that introspection of the stack trace for error handling will do a lot of harm to you. If you need separate actions for individual lines, use them in separate try-catch blocks.

You can also just have a simple state for saving variables so you can check its value to determine how much you got. I think this will work much better.

 int state = 0; try { step1(); state = 1; step2(); state = 2; .... } catch (Exception e) { if (state == 2) .... 

}


Edit: Downvoters, please note, I started saying that this is a bad idea; -)

0
source

All Articles