c# - 从 catch block 中抛出嵌套异常……这明智吗?

标签 c# .net exception

我想在我的库中实现自定义异常处理,以便我知道异常发生的位置,所以我这样做:

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/

相关文章:

.net - 等待队列与就绪队列

c# - 自定义控件属性作为枚举

python - 在上下文管理器 __enter__() 中捕获异常

c# - 使用下级用户名检索用户主体对象

c# - 如何使用 C# 监视进程的 IO 事件?

javascript - 用于 bool 检查的 Razor 语法

c# - ICollection - 获取单个值

c++ - 如果在并行部分执行会抛出错误吗?

c++ - 编写 "anti-lack of memory"异常安全代码

c# - 企业库 5.0 强行关闭事件连接