当我使用Try/Catch时,如果没有检测到错误且没有Catch,有没有像If/Else那样运行代码的方法?
try
{
//Code to check
}
catch(Exception ex)
{
//Code here if an error
}
//Code that I want to run if it's all OK ??
finally
{
//Code that runs always
}
Run Code Online (Sandbox Code Playgroud)
Joe*_*oey 23
在try块的末尾添加代码.显然,如果之前没有例外,你将只能到达那里:
try {
// code to check
// code that you want to run if it's all ok
} catch {
// error
} finally {
// cleanup
}
Run Code Online (Sandbox Code Playgroud)
你可能应该改变你的捕获方式,你只捕获你期望的异常,而不是弄平一切,这可能包括你想要运行的代码中抛出的异常,如果一切正常«.
Pol*_*ial 11
如果您需要它在try代码成功时始终执行,请将其放在try块的末尾.只要try块中的前一个代码在没有异常的情况下运行,它就会运行.
try
{
// normal code
// code to run if try stuff succeeds
}
catch (...)
{
// handler code
}
finally
{
// finally code
}
Run Code Online (Sandbox Code Playgroud)
如果您需要替代异常处理"成功"代码,您可以始终嵌套您的try/catches:
try
{
// normal code
try
{
// code to run if try stuff succeeds
}
catch (...)
{
// catch for the "succeded" code.
}
}
catch (...)
{
// handler code
// exceptions from inner handler don't trigger this
}
finally
{
// finally code
}
Run Code Online (Sandbox Code Playgroud)
如果您的"成功"代码必须在finally之后执行,请使用变量:
bool caught = false;
try
{
// ...
}
catch (...)
{
caught = true;
}
finally
{
// ...
}
if(!caught)
{
// code to run if not caught
}
Run Code Online (Sandbox Code Playgroud)
只需将它放在可能引发异常的代码之后.
如果抛出异常,它将不会运行,如果没有抛出异常,它将运行.
try
{
// Code to check
// Code that I want to run if it's all OK ?? <-- here
}
catch(Exception ex)
{
// Code here if an error
}
finally
{
// Code that runs always
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9386 次 |
| 最近记录: |