我想在我的库中实现自定义异常处理,以便我知道异常发生的位置,所以我这样做:
try
{
DoSomething();
}
catch(Exception ex)
{
//LibraryException refers to any exception in the libraries exception hierarchy
throw new LibraryException(ex.Message, ex);
}
应该避免这种情况吗?
它对性能有影响吗?
捕获、嵌套和重新抛出异常的含义是什么?
最佳答案
唯一的潜在问题是您捕获了一个非特定的Exception
,因此不符合exception handling guidelines .
以下其中一项更符合这些准则:
try
{
DoSomething();
}
catch(SomeException ex)
{
throw new LibraryException(ex.Message, ex);
}
或:
try
{
DoSomething();
}
catch(Exception ex)
{
if (ex is SomeException || ex is SomeOtherException)
{
throw new LibraryException(ex.Message, ex);
}
throw;
}
至于性能,一旦抛出异常,就会发生异常情况,您可能不关心包装它的小额外开销。
来自评论:
in most cases when a library chooses to wrap exceptions it will wrap all exceptions that are thrown outside of the scope of the library, ...
我不同意这一点,尽管这确实是主观的。 SqlMembershipProvider
是包装异常的库的一个示例,它将一些特定的异常包装在 ProviderException
中,例如:
try
{
new Regex(this._PasswordStrengthRegularExpression);
}
catch (ArgumentException exception)
{
throw new ProviderException(exception.Message, exception);
}
但是调用方无法处理的其他异常(例如 SqlException
)会展开传播。
关于c# - 从 catch block 中抛出嵌套异常……这明智吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12603295/