I would like to know how try {} catch {} traces of blocks and stacks work.
I read this wonderful article on exception handling antiviruses and found the following paragraph:
catch (NoSuchMethodException e) { throw new MyServiceException("Blah: " + e.getMessage()); }
This destroys the stack trace of the original exception and is always incorrect.
After that, I realized that I really don't know how try/catch works. My understanding is as follows. Consider an example:
void top() { try { f(); } catch (MyException ex) { handleIt(); } finally { cleanup(); } } void f() { g(); } void g() { throw new MyException(); }
When I call top() , the chain of calls top -> f -> g leaves two stack frames in the call stack (for the top and f functions). When the exception is expressed in g , the program bubbles up the execution stack until it finds a try/catch that handles the exception. In the meantime, it frees up the stack frames and attaches the stack trace information to some βmagicβ object that can be passed to catch , and the stack trace can be printed.
How does he know that the called function is "surrounded" by the try / catch block? Is this information related to the stack frame? For example, a pointer to an error processing block (some switches select the corresponding catch ) and a pointer to a finally block? Why is e.getMessage() destructive in the above example (see comments)?
Notice, I know how to use try / catch and exceptions, I want to know how it works inside.
source share