尝试捕捉错误处理的最佳做法 [英] Best Practice for Try Catch Error Handling
本文介绍了尝试捕捉错误处理的最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
private SecurityLevel ApiGetSecurityLevel()
{
try
{
return _BioidInstance.GetSecurityLevel();
}
catch
{
return SecurityLevel.High;
}
}
有没有更好的方式这样做,所以我不会返回不正确的值?我不能更改SecurityLevel枚举。
解决方案
不要捕获异常。允许异常起泡强制呼叫者/呼叫者处理设置默认安全性值。
如果您真的要返回值,则使用 Nullable< SecurityLevel>
或 SecurityLevel?
。
private SecurityLevel? ApiGetSecurityLevel(){
try {
return _BioidInstance.GetSecurityLevel();
}
catch {
return null;
}
}
然后使用as:
if(ApiGetSecurityLevel()。HasValue == false){
//使用默认安全级别
}
I'm trying to avoid returning an incorrect value when in the catch but I'm having trouble finding a better solution than this:
private SecurityLevel ApiGetSecurityLevel()
{
try
{
return _BioidInstance.GetSecurityLevel();
}
catch
{
return SecurityLevel.High;
}
}
Is there a better way of doing this so I don't return incorrect values? I can't change the SecurityLevel enum.
解决方案
Do not catch the exception. Allow the exception to "bubble-up" to force the caller/callers to handle setting the default security value.
If you really want to return a value then use Nullable<SecurityLevel>
or SecurityLevel?
.
private SecurityLevel? ApiGetSecurityLevel() {
try {
return _BioidInstance.GetSecurityLevel();
}
catch {
return null;
}
}
Then use as:
if (ApiGetSecurityLevel().HasValue == false) {
// use default security level
}
这篇关于尝试捕捉错误处理的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文