Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when running inside a catch block

Tags:

c#

catch-block

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?
    }
}
like image 921
bboyle1234 Avatar asked Aug 26 '14 14:08

bboyle1234


People also ask

Can I continue in a catch block?

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; ?

What happens if I put the system out in the catch block?

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.

Does try catch stop execution?

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) .

How do you stop the execution in catch block?

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.


1 Answers

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.

like image 107
Servy Avatar answered Sep 17 '22 11:09

Servy