Creating generic exceptions?
Rob asked the following question on StackOverflow:
How do I create an exception of a particular type from a generic method.
The best solution found on the StackOverflow site was this:
This is great - but there is a gotcha - it is possible to create an exception class that inherits from Exception, that does not implement the message constructor:
public class MyException : Exception
{
public MyException()
{
}
}
Given the above exception the following will work:
Exception e1 = GenerateException<Exception>("Test message 1");
But this will throw a MethodMissingException:
MyException e2 = GenerateException<MyException>("Test message 2");
How do I create an exception of a particular type from a generic method.
The best solution found on the StackOverflow site was this:
static ExType TestException<ExType>(string message) where ExType:Exception
{
ExType ex = (ExType)Activator.CreateInstance(typeof(ExType), message);
return ex;
}
This is great - but there is a gotcha - it is possible to create an exception class that inherits from Exception, that does not implement the message constructor:
public class MyException : Exception
{
public MyException()
{
}
}
Given the above exception the following will work:
Exception e1 = GenerateException<Exception>("Test message 1");
But this will throw a MethodMissingException:
MyException e2 = GenerateException<MyException>("Test message 2");