How to pass an exception type as a parameter?

I would like to have a method that gets the type of exception (i.e. the parameter passed must be a class that implements System.Exception).

What is the right way to do this?

Below I DO NOT want:

public void SetException(Exception e)

... which requires an exception instance. I want to pass an exception type likeInvalidProgramException


Edit: To clarify what I want to do, I want to be able to track how many times I saw exceptions for 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 do not want to pass an instance of the exception, but track it by the type of exception.

+4
source share
5 answers

Sounds like you need a generic method

public void SetException<TException>() where TException : Exception
{
    ExceptionCounts[typeof(TException)]++;
}

You can call him

SetException<InvalidProgramException>();

Edit:

Dictionary<Type, int> ExceptionCounts;
public void ExceptionSeen(Type type)
{
    ExceptionCounts[type]++;
}

Name him

ExceptionSeen(typeof(MyException));

ExceptionSeen(ex.GetType());
+2

, "" paramteer, , , , :

public void SetException(Type t) {
    if (!typeof(Exception).IsAssignableFrom(t)) {
       throw new ArgumentException("t");
    }
}
+1

Define a generic method that the instance does not accept, then use a generic type constraint to force it to inherit from Exception:

public void SetException<T>() where T : Exception
{
}
+1
source

Like this:

public void SetException(Type type)

SetException(typeof(InvalidProgramException))
// or
SetException(e.GetType)

Other options are using generics to help.

public void SetException<T>()    
SetException<InvalidProgramException>()

or

public void SetException<T>(T exception)    
SetException(e);
0
source

you can create your own class that inherits the base exception, i.e. an exception class, and then you can pass any type of exception to your method according to the type of parameters of your custom class that you have already created.

-1
source

All Articles