美好的一天!
我写简单的控制台程序。它有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);
}
}
}
当异常发生时 - 它会抓住GetSomething。所以,我写了一些值。但是我需要程序在异常后仍然运行。 但是在GetSomething方法中捕获之后,它会转到Main func和program exits的Exception ex;
如何在GetSomething方法中捕获异常后仍然运行该程序? 谢谢!
答案 0 :(得分:4)
如果你想要的是捕获异常并在失败点继续执行(可能是调用堆栈中的几层)并且可能重试失败的语句,那么你很不幸。
调用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() ;
}
}
答案 1 :(得分:2)
在.NET中无法执行此操作。抛出异常时,控制退出当前点并继续执行它可以在调用堆栈中找到的第一个catch
语句,或退出程序,从而消除执行到此时的调用堆栈。这是异常行为定义的一部分。
您可以通过Work
分解正在执行的流程,并逐个处理每个项目,以实现与您所要求的相同的效果。换句话说,请尝试
Work(array)
foreach(var item in array)
{
try { WorkSingle(item); }
catch { continue; }
}
答案 2 :(得分:1)
你可以使用try,catch和finally: