Simon
Simon

Reputation: 34840

How to throw a exception that doesnt inherit from Exception?

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
}

Upvotes: 0

Views: 505

Answers (2)

JaredPar
JaredPar

Reputation: 754745

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

Upvotes: 13

itowlson
itowlson

Reputation: 74802

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.

Upvotes: 5

Related Questions