c#只在其他代码成功时执行代码



假设我有

Method1(); // might return error
Method2(); // should only be executed if previous line successful

我可以使用trycatch,但是我仍然希望错误发生,我只是不希望Method2()运行,如果发生任何错误。

有一个"模板"对于如下所示的函数:

bool TrySomething( out int returnValue )

,如果成功则返回true,否则返回false。只有当返回的bool值为true时,returnValue才有效。所以你可以这样使用:

if( TrySomething(out int someValue) )
{
Method2( someValue );
}

不同类型的TryParse方法就是这样的例子。


另一种方法是如果Method1抛出异常:

Method1();
// If Method1 throws an exception, Method2 will not be executed.
// The control flow will be redirected to the "next" catch block
// that handles the exception type or if none of those exist crash 
// the app.
Method2();

所以,即使你没有用try/catch块包围Method1,控制流也不会继续执行Method2

如果使用try/catch块,Method2也将被执行:

try
{
Method1(); // throws 
Method2(); // won't execute
}
catch(SomeException ex)
{
// Control flow will continue here.
// Handle that exception
}
finally // optional
{
// This will be executed regardless of whether there was an exception or not.
}

进一步阅读:

  • 异常和异常处理

根据@ProgrammingLlama的建议,你应该这样做:

try {
MethodWithErrorOrException();
MethodAfter();
}
catch (Exception) {
// Handling
}
finally {
MethodAlwaysCalled();
}

自然地methodwitherrororeexception()应该抛出Exception。

或者,您必须使用方法MethodWithErrorOrException()的返回值来了解是否一切都成功,但这不是最优雅的解决方案。

让Method1在出错时返回false。你可以这样使用:

if(Method1()){Method2();}

最新更新