2009-10-26 63 views
0

我想在下面的代码的空catch块中测试一些异常处理逻辑。如何抛出一个不会从Exception继承的异常?

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 
} 
+0

一个非常重要的一点是,'犯规继承Exception'是可能的,但只有在CLR1.0平台,或与[WrapNonExceptionThrows](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.runtimecompatibilityattribute.wrapnonexceptionthrows.aspx)关闭 - 这两个都很少见。 – quetzalcoatl 2013-06-14 13:20:10

回答

13

从CLR 2.0开始,这不是您需要担心的情​​况。 CLR现在将自动包含所有不从System.Exception派生的异常,并使用RuntimeWrappedExceptionDocumentation)类型的新异常。

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

唯一缺少
+0

谢谢Jared解决了我的问题。 – Simon 2009-10-26 01:58:21

5

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

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

+0

+1帮助信息 – Simon 2009-10-26 01:59:23