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

本文关键字:恢复 执行 捕获异常 | 更新日期: 2023-09-27 18:30:14

您好!

我写一个简单的控制台程序。它有funcMain()和类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);
        }
    }
}

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

如何在GetSomething方法中捕获异常后使程序仍在运行?非常感谢。

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

如果您想要的是捕获异常并在失败点(可能在调用堆栈的几层)继续执行,并可能重试失败的语句,那么您就太倒霉了。

一旦调用了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.

如果不执行上述任一操作,则在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() ;
  }
}

这种行为在.NET中是不可能的。当抛出异常时,控件会退出当前点,并继续执行它在调用堆栈中可以找到的第一条catch语句,或者退出程序,从而在该点之前取消调用堆栈的执行。这是异常行为定义的一部分。

相反,您可以分解Work正在进行的过程,并一次处理一个项目,以实现与您所要求的效果相同的效果。换句话说,尝试而不是Work(array)

foreach(var item in array)
{
    try { WorkSingle(item); }
    catch { continue; }
}

您可以使用try、catch和finally:

http://www.dotnetperls.com/finally

http://msdn.microsoft.com/es-es/library/dszsf989.aspx