Pra*_*nth 1 .net c# exception try-catch
考虑以下函数。我是用C#写的。
public void Test()
{
statement1;
try
{
statement2;
}
catch (Exception)
{
//Exception caught
}
}
Run Code Online (Sandbox Code Playgroud)
statement1我只想在没有引起异常的情况下执行statement2。是否可以statement1只在statement2 不抛出任何异常的情况下执行?
是的,你可以通过这种方式轻松做到
public void Test()
{
try
{
statement2;
statement1;
}
catch (Exception)
{
//Exception caught
}
}
Run Code Online (Sandbox Code Playgroud)
如果statement2抛出一些异常,statement1将不会运行。
另一种不太酷的方法是使用变量
public void Test()
{
bool completed=false;
try
{
statement2;
completed=true;
}
catch (Exception)
{
//Exception caught
}
if (completed)
statement1;
}
Run Code Online (Sandbox Code Playgroud)