I would like to have a method that receives a type of exception (i.e., the parameter passed must be a class that implements System.Exception).
What is the right way to do this?
The following is NOT what I want:
public void SetException(Exception e)
... that requires an instance of an exception. I want to pass a type of exception like InvalidProgramException
Edit: To further explain what I want to do, I want to be able to track how many times I have seen an exception of each type before. So I want to be able to do something like:
Dictionary<ExceptionTypeThing, int> ExceptionCounts;
public void ExceptionSeen(ExceptionTypeThing e)
{
// Assume initialization
ExceptionCounts[e]++;
}
ExceptionSeen(InvalidProgramException);
I don't want to pass an instance of the exception, but rather track it by type of exception.
Sounds like you need a generic method
public void SetException<TException>() where TException : Exception
{
ExceptionCounts[typeof(TException)]++;
}
You can call it as
SetException<InvalidProgramException>();
Edit:
Dictionary<Type, int> ExceptionCounts;
public void ExceptionSeen(Type type)
{
ExceptionCounts[type]++;
}
Call it as
ExceptionSeen(typeof(MyException));
Or if you have the exception instance already
ExceptionSeen(ex.GetType());
Define a generic method that does not take an instance, then use the generic type constraint to force it to inherit from Exception
:
public void SetException<T>() where T : Exception
{
}
If you just want to pass a type, specify 'Type' as the paramteer type, then if you want to make sure that is is of exception type you need to check the type at runtime:
public void SetException(Type t) {
if (!typeof(Exception).IsAssignableFrom(t)) {
throw new ArgumentException("t");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With