【问题标题】:How to throw a exception that doesnt inherit from Exception?如何抛出不从 Exception 继承的异常?
【发布时间】:2009-10-26 01:44:20
【问题描述】:

我想在下面代码的空catch块中测试一些异常处理逻辑。

try
{
    //Do Some stuff that throws a exception 
    //This is the code i need
}
catch (Exception)
{
    //Handle things that inherits from Exception
}
catch
{
    //Handle things that dont inherits from Exception
    //Want to test this code
}

【问题讨论】:

  • 缺少一个非常重要的注意事项是doesnt inherit from Exception 是可能的,但只能在 CLR1.0 平台上,或者在关闭WrapNonExceptionThrows 的情况下 - 这两种情况都很少见。

标签: .net exception exception-handling


【解决方案1】:

从 CLR 2.0 开始,您无需担心这种情况。现在,CLR 将使用 RuntimeWrappedException (Documentation) 类型的新异常自动包装不是从 System.Exception 派生的所有异常。

可以通过启用一定程度的应用程序兼容性来禁用这种包装,但这肯定不是正常或常见的情况

【讨论】:

    【解决方案2】:

    您不能编写在 C# 中引发非异常的代码。您需要用 IL(并使用 ILASM 编译)或 C++/CLI 编写它。

    但是,老实说,我不会担心这种情况。框架中没有使用抛出非异常的能力,我怀疑它在许多第三方代码中使用。我只会在您使用知道抛出非异常的库时解决这个问题。

    【讨论】:

      猜你喜欢
      • 2015-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-03
      • 1970-01-01
      • 2014-01-25
      • 2012-03-12
      • 1970-01-01
      相关资源
      最近更新 更多