C# 如何捕获异常并恢复执行

Adm*_*and 2 c# exception

再会!

我编写简单的控制台程序。它有 func Main() 和类 Adapter;

一些简单的代码解释了它是如何工作的:

void Main()
{
    try
    {
        Work(array);
        //subcribing at some events;
        Application.Run();  
    }
    catch(Exception ex)
    {
        //write to log;
    }
}
class Adapter
{
    ....
    public void GetSomething()
    {
        try
        {
            ...some work and exception goes here;
        }
        catch(Exception ex)
        {
            //catch exception and do Work:
            Work(array);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当异常发生时,它会在 GetSomething 处捕获。所以,我写了一些值。但我需要程序在异常后仍然运行。但是在 GetSomething 方法中 catch 后,它会转到 Main func 处的 Exception ex 并且程序退出;

如何在 GetSomething 方法中捕获异常后程序仍然运行?谢谢你!

Nic*_*rey 5

如果您想要捕获异常并在失败点(可能位于调用堆栈中的几层)继续执行,并可能重试失败的语句,那么您就很不走运了。

一旦catch调用您的子句,堆栈就已展开到该点。您可以通过某种方式处理异常,然后选择零个或一个

  • 继续异常通过throw ;
  • 通过重新抛出异常throw e;
  • 通过抛出一个新的异常throw new SomeException();

如果未选择上述其中一项,则将从块后面的点继续执行try/catch/finally。例如:

    try
    {
      DoSomethingThatMightThrowAnException() ;
    }
    catch ( Exception e )
    {

      DoSomethingToHandleTheExceptionHere() ;

      // Then, choose zero or one of the following:
      throw                  ; // current exception is continue with original stack trace
      throw e                ; // current exception is re-thrown with new stack trace originating here
      throw new Exception()  ; // a new exception is thrown with its stack trace originating here
      throw new Exception(e) ; // a new exception is thrown as above, with the original exception as the inner exception

    }
    finally
    {
       // regardless of whether or not an exception was thrown,
       // code in the finally block is always executed after the try
       // (and the catch block, if it was invoked)
    }

    // if you didn't throw, execution continues at this point.
Run Code Online (Sandbox Code Playgroud)

如果您不执行上述操作之一,则将从try/catch/finally块后面的语句处继续执行。

就重试而言,您能做的最好的事情是这样的:

// retry operation at most 3
int number_of_retries = 5 ;
for ( int i = 0 ; i < number_of_retries ; ++i )
{
  try
  {

     DoSomethingThatMightThrowAnException() ;

     break ; // exit the loop on success

  }
  catch( Exception e )
  {

     Log.Error("well...that didn't work") ;

     ExecuteRecoveryCode() ;

  }

}
Run Code Online (Sandbox Code Playgroud)