low*_*ern 58 .net c# exception-handling
在catch块中有一个return语句是错误的吗?有哪些替代方案?
即:
public bool SomeFunction()
{
try
{
//somecode
return true;
}
catch(Exception ex)
{
MessageBox.Show(ex.message);
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*off 20
一种替代方法是将返回值存储在临时变量中:
public bool SomeFunction()
{
bool success = true;
try
{
//somecode
}
catch(Exception ex)
{
MessageBox.Show(ex.message);
success = false;
}
return success;
}
Run Code Online (Sandbox Code Playgroud)
但就个人而言,我发现你编写它的方式(带有一个catch-all catch语句)更具可读性.另一方面,如果您期望一个特定的异常,并且您可能有多个路径可以返回成功...
try
{
DoTheImportantThing();
DoTheOtherThingThatMightFailButWeDontCare();
}
catch (DontCareAboutItException ex)
{
log.Info(ex);
}
catch (Exception ex)
{
log.Error(ex);
return false;
}
return true;
Run Code Online (Sandbox Code Playgroud)
然后在我看来,你最好尽可能接近尾声.
作为旁注,根据应用程序,考虑记录您捕获的异常,而不是仅仅向用户显示它们.记录的异常比用户重新计算发生的事情要可靠得多.
Dar*_*rov 11
如果在try块中已经有一个return语句,我可能会把另一个返回放在函数的末尾:
try
{
//somecode
return true;
}
catch(Exception ex)
{
MessageBox.Show(ex.message);
}
return false;
Run Code Online (Sandbox Code Playgroud)
这是为了避免多次返回,如果需要处理多个异常.
没关系,只需要记住,一些代码可以在返回指令后执行(返回值ll被兑现).
try
{
return;
}
catch(Exception ex)
{
return;
}
finally
{
//some code
}
Run Code Online (Sandbox Code Playgroud)
public bool SomeFunction()
{
try
{
//somecode
return true;
}
catch(Exception ex)
{
MessageBox.Show(ex.message);
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
我个人将return语句放在方法的底部而不是catch块中.但两者都很好.这完全取决于组织中的可读性(主观)和指导原则.
| 归档时间: |
|
| 查看次数: |
42783 次 |
| 最近记录: |