即使异常在调用堆栈中处理得更高,是否也可以强制执行 try-catch?

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

示例 - A() -> B() -> C()

C() 包含一个 try-catch,并简单地记录异常并继续执行,因为 throw; 被注释掉了。

因此 A() 中的 try/catch 不会触发。

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
}

是否有任何机制强制 A() catch 捕获在它之后的调用堆栈中引发的任何异常?

我问的原因是我需要确保报告任何付款问题,但 B(); 的大量代码中必须有 40 多个尝试捕获;包含!

没有

没有。您需要信任 B() 来完成它的工作并准确报告结果。

对于 B() 也没有任何保护:

public bool B()
{
   var failed = ImportantOperation();

   if(failed) 
      // oops
      return true;
   else
      return true;
}

如果您不信任代码,请自己编写代码或找一个您可以信任的代码提供商。

不,您无法捕获已处理的异常,除非该异常被重新抛出:

try
{
   B();
}
catch(Exception e)
{
    // handle the exception

    throw; // then re-throw it.
}

如果是为了记录目的,您可能正在寻找 AppDomain.FirstChanceException 事件,它使您能够 'catch' 异常,即使它们已被处理。