我有一个Dictionary<string, T>
私有字段(users
),其中string
键代表用户名。我为这个类写了一些方法,例如GetValue(string userid)
方法返回与指定用户名关联的T
对象。处理自定义类中的异常
我会处理这个类中可能出现的异常,这些异常是由Dictionary引起的。例如:
- 如果指定键为空,则
Dictionary
抛出ArgumentNullException
; - 如果指定的键不存在于
Dictionary
中,则会抛出KeyNotFoundException
。
的第一种方法可以赶上由Dictionary
抛出的异常,并重新抛出同样的例外或抛出自定义异常。
public T GetValue(string userid)
{
try
{
return users[userid];
}
catch(ArgumentNullException ex1)
{
// re-throw the same exception
}
catch(KeyNotFoundException ex2)
{
throw new UserIdNotFoundException("The specified userid does not exist.", ex2); // custom exception
}
}
的第二种方法可避免捕捉异常,但检查导致他们的条件,并抛出适当的例外。
public T GetValue(string userid)
{
if (userid != null)
{
if(users.ContainsKey(userid))
return users[userid];
else throw new UserIdNotFoundException("The specified userid does not exist.", ex2); // custom exception
}
else throw new ArgumentNullException(...);
}
的第三种方法是类似于第二之一,但它使用了Dictionary
的TryGetValue
方法。
public T GetValue(string userid)
{
if (userid != null)
{
T value;
if(users.TryGetValue(userid, out value))
return value;
else throw new UserIdNotFoundException("The specified userid does not exist.", ex2); // custom exception
}
else throw new ArgumentNullException(...);
}
每种方法的优点和缺点是什么? 的best practices for handling exceptions说:
如果该事件是真正的例外,是错误的,因为使用更少的代码在正常情况下,执行异常 处理比较好... 如果事件发生日常使用编程的方法来检查 错误比较好...
在我的情况下GetValue(string userid)
方法将被调用很少,但是类的潜在用户可以使用它非常频繁。