Try Catch错误处理的最佳实践

Rob*_*ert 4 .net exception-handling exception

我试图避免在捕获时返回不正确的值,但我找不到比这更好的解决方案:

    private SecurityLevel ApiGetSecurityLevel()
    {
        try
        {
            return _BioidInstance.GetSecurityLevel();
        }
        catch
        { 
            return SecurityLevel.High;
        }
    }
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法这样做,所以我不返回不正确的值?我无法更改SecurityLevel枚举.

AMi*_*ico 12

不要抓住异常.允许异常"冒泡"以强制调用者/调用者处理设置默认安全值.


如果你真的想要返回一个值,那么使用Nullable<SecurityLevel>SecurityLevel?.

private SecurityLevel? ApiGetSecurityLevel() { 
    try { 
        return _BioidInstance.GetSecurityLevel(); 
    } 
    catch {  
        return null; 
    } 
} 
Run Code Online (Sandbox Code Playgroud)

然后用作:

if (ApiGetSecurityLevel().HasValue == false) {
    // use default security level
}
Run Code Online (Sandbox Code Playgroud)


All*_*enG 6

这可能是应用程序失败的情况吗?也就是说,如果无法确定SecurityLevel,用户应该无法继续?

如果是这样,为什么不重新抛出并让UI处理它(或让它记录,但你的商店工作)?

如果应用程序应该能够继续,请选择(并记录)一些默认值并完成您正在执行的操作.


Dav*_*sky 5

首先,只要GetSecurityLevel返回a ,就没有理由尝试/ catch SecurityLevel.编译器会在那里发现任何问题.

其次,这不是try/catch的好用.Try/catch不应该用于正常的控制流程,仅适用于特殊情况.

如果由于某种原因,GetSecurityLevel()不返回SecurityLevel枚举类型:

private SecurityLevel ApiGetSecurityLevel()
    {
        object securityLevel = _BioidInstance.GetSecurityLevel();
        if (securityLevel is SecurityLevel)
        {
             return _BioidInstance.GetSecurityLevel();
        }
        else
        {
             throw new Exception("Invalid SecurityLevel");
        }
    }
Run Code Online (Sandbox Code Playgroud)