Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a type of exception as a parameter?

Tags:

c#

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.

like image 719
gnychis Avatar asked May 03 '15 19:05

gnychis


3 Answers

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());
like image 159
Sriram Sakthivel Avatar answered Oct 19 '22 21:10

Sriram Sakthivel


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
{
}
like image 41
BJ Myers Avatar answered Oct 19 '22 22:10

BJ Myers


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");
    }
}
like image 29
Mehrzad Chehraz Avatar answered Oct 19 '22 20:10

Mehrzad Chehraz