这在异常处理中是一种更好的做法吗?

mus*_*bar 2 c# exception-handling

如果我有一个特定的例外,我预计它会发生; 并且为了处理它,例如我选择在其出现时显示错误消息,这样做会更好,为什么?

解释性代码:

try
{
    string result = dictionary[key];
}
catch (KeyNotFoundException e) 
{ 
    //display error
}
Run Code Online (Sandbox Code Playgroud)

要么:

if(!dictionary.ContainsKey(key))
{
    //display error
}
Run Code Online (Sandbox Code Playgroud)

the*_*oop 12

通常,异常用于指示异常情况 - 通常不会发生的情况,但您的程序仍需要优雅地处理(例如,文件无法访问或只读,网络连接断开).正常控制流(如检查字典中的值)如果存在具有相同效果而不使用异常的等效函数,则不应使用异常.

在代码中使用额外的try/catch语句也会降低其可读性,并且在代码块周围使用异常处理程序会对CLR造成某些限制,从而导致性能下降.

在您的示例中,如果预期字典将具有某个键值,我会做类似的事情

string result;
if (!dictionary.TryGetValue(key, out result)
{
    // display error
    return;   // or throw a specific exception if it really is a fatal error
}

// continue normal processing
Run Code Online (Sandbox Code Playgroud)

这比在元素访问中使用异常处理程序要清楚得多


Guf*_*ffa 7

都不是.

第二种选择比第一种更好.正如您所期望的那样,正常情况下,最好避免异常.例外情况应该优先用于特殊情况,即您无法轻易预测和测试的情况.

然而,最好的选择是TryGetValue方法,因为它同时检查和获取:

if (dictionary.TryGetValue(key, out result)) {
   // use the result
} else {
   // display error
}
Run Code Online (Sandbox Code Playgroud)