问题
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