从catch块抛出嵌套异常...这是明智的?这是、嵌套、抛出、明智

2023-09-06 17:03:07 作者:上線啦

我要实现自定义的异常处理在我的图书馆,让我知道发生了异常的地方,所以我这样做:

I want to implement custom exception handling in my library so that I know where an exception occurred, so I am doing this:

try
{
    DoSomething();
}
catch(Exception ex)
{
    //LibraryException refers to any exception in the libraries exception hierarchy
    throw new LibraryException(ex.Message, ex);
}

这应该避免?

Should this be avoided?

是否有任何性能影响?

什么是醒目的影响,嵌套和重新抛出异常?

What are the implications of catching, nesting and re-throwing exceptions?

推荐答案

唯一潜在的问题是,你赶上一个非特异性异常,所以不符合在异常处理准则。

The only potential problem is that you're catching a non-specific Exception, so not conforming to the exception handling guidelines.

以下情况之一会比较一致这些准则:

One of the following would be more conformant with these 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;
}

至于性能,一旦异常被抛出,一些特殊情况发生,你可能不关心它包裹的小额外的开销。

As for performance, once an Exception has been thrown, something exceptional has happened, and you probably don't care about the small additional overhead of wrapping it.

从评论:

在大多数情况下,当一个库选择来包装异常将包被的库的范围,...

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 ,例如:

I disagree with this, though it's admittedly subjective. One example of a library that wraps exceptions is SqlMembershipProvider, which wraps some specific exceptions in a ProviderException, e.g.:

try
{
    new Regex(this._PasswordStrengthRegularExpression);
}
catch (ArgumentException exception)
{
    throw new ProviderException(exception.Message, exception);
}

但其他例外,如 SQLEXCEPTION ,一个来电,不能指望处理传播展开。

but other exceptions such as SqlException that a caller can't be expected to handle are propagated unwrapped.