返回try &Catch vs return in最后
本文关键字:return in 最后 vs Catch try 返回 | 更新日期: 2023-09-27 18:06:57
是否存在风险?哪个更好?还是那种打印出来扔飞镖就能决定的东西?
我现在想这样做,因为我知道最后是如何工作的:
try {
stuff that changes something...
}
catch (System.Exception ex) {
something.worked = false;
something.err = ex.Message;
}
finally {
stuff.close();
return something;
}
但是我已经看到了:
try {
stuff that changes something...
return something;
}
catch (System.Exception ex) {
something.worked = false;
something.err = ex.Message;
return something;
}
finally {
stuff.close();
}
你不能从finally
到return
。你会得到编译错误:
控件不能离开finally子句
的主体。
如果目标类实现了IDisposable
,那么我将下一步:
using (stuff s = new stuff())
{
return stuff;
}
或
using (stuff s = new stuff())
{
try
{
// do stuff
return stuff;
}
catch (Exception ex)
{
// do logging or another stuff
return something;
}
}
如果需要/可能的话,将为您呼叫Dispose()
。
我个人不会这样做,我会使用
try {
stuff that changes something...
}
catch (System.Exception ex) {
something.worked = false;
something.err = ex.Message;
}
finally {
stuff.close();
}
return something;
同样在finally
语句中,检查您是否需要关闭/处置对象,因为如果它们失败了,它们可能从未被打开/设置过。
也可以在这里看到从try catch finally块内返回是不好的做法吗?
第二种方法没有风险。但是它允许您在异常情况下返回不同的值。