How to throw a exception that doesnt inherit from Exception?

折月煮酒 提交于 2019-12-13 03:47:03

问题


I would like to test some exception handling logic in the empty catch block of the below code.

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
}

回答1:


Starting with CLR 2.0 this is not a scenario that you need to worry about. The CLR will now automatically wrap all exceptions which do not derive from System.Exception with a new Exception of type RuntimeWrappedException (Documentation).

This wrapping can be disabled by enabling a level of application compatibility but it is certainly not the normal or common case




回答2:


You cannot write code that throws a non-Exception in C#. You would need to write it in IL (and compile using ILASM) or C++/CLI.

But, to be honest, I wouldn't worry about this scenario. The ability to throw non-Exceptions is not used in the framework, and I doubt it is used in much third-party code. I would only address this if you are using a library which you know throws non-Exceptions.



来源:https://stackoverflow.com/questions/1622755/how-to-throw-a-exception-that-doesnt-inherit-from-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!