Search code examples
c#exceptiontry-catchthrow

Is it possible to force a try-catch even if exceptions are handled higher in the call stack?


EXAMPLE - A() -> B() -> C()

C() contains a try-catch, and simply logs the exception and carries on with execution, because the throw; was commented out.

Therefore the try/catch in A() won't trigger.

public void A(){
   try{
      B();
   }
   catch(Exception e){
      //something really important
   }
}


public void B(){
   try{
      throw new Exception("test");
   }
   catch(Exception e){
      Log.Error($"Error - {e.InnerException}");
      //throw;
   }

   //further code
}

Is there any mechanism that forces A() catch to capture ANY exception raised in the call-stack following it?

The reason I ask is I need to ensure any issues with a Payment are reported but there must be 40+ try catches in the masses of code that B(); contains!


Solution

  • No, you can't catch an already handled exception unless that exception is rethrown:

    try
    {
       B();
    }
    catch(Exception e)
    {
        // handle the exception
    
        throw; // then re-throw it.
    }
    

    If it is for logging purposes, you might be looking for the AppDomain.FirstChanceException event, which gives you the ability to 'catch' exceptions even when they are handled.