How do I detect when the currently-executing code is being called from within a catch block?
void SomeFunction()
{
// how do I detect whether I am being called from within a catch block?
}
EDIT:
For those asking, I wanted to implement a class like this, never mind the error bubbling logic: On writing this code sample, I'm getting a compiler error "A throw statement with no arguments is not allowed outside of a catch clause" so that kinda destroys my idea anyway.
public class ErrorManager {
public void OnException(Exception ex) {
LogException(ex);
if (IsInsideCatchBlockAlready()) {
// don't destroy the stack trace,
// but do make sure the error gets bubbled up
// through the hierarchy of components
throw;
} else {
// throw the error to make it bubble up
// through the hierarchy of components
throw ex;
}
}
void LogException(Exception ex) {
// Log the exception
}
bool IsInsideCatchBlockAlready() {
// How do I implement this?
}
}
You only need continue if you have code after it, and want start at the top of the loop again. Maybe you actually want if (e. Number != 64) throw; ?
Answer: When an exception is thrown in the catch block, then the program will stop the execution. In case the program has to continue, then there has to be a separate try-catch block to handle the exception raised in the catch block.
The “try… First, the code in try {...} is executed. If there were no errors, then catch (err) is ignored: the execution reaches the end of try and goes on, skipping catch . If an error occurs, then the try execution is stopped, and control flows to the beginning of catch (err) .
You can throw the exception after catching it speakTo* methods. This will stop execution of code in methods calling speakTo* and their catch block will be executed. Show activity on this post. You need to propagate your Exceptions to the main class to completely stop the execution of a program.
You don't. There is no way to know if, should you throw an exception, it would be caught or crash the program. You could potentially make a guess at compile time with a code analysis tool, but that wouldn't be an option while the code is running.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With