如何抛出不从Exception继承的异常?

Sim*_*mon 0 .net exception-handling exception

我想在下面的代码的空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
}
Run Code Online (Sandbox Code Playgroud)

Jar*_*Par 13

从CLR 2.0开始,这不是您需要担心的情​​况.现在,CLR将自动包装所有不是从System.Exception派生的异常,并带有新的Exception of type RuntimeWrappedException(Documentation).

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


ito*_*son 5

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

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