If I have a C# List<string>
of exception names (eg. InternalServerErrorException, ConflictException, etc), how would I go about instantiating and throwing the specific exception with nothing more than the string value?
To clarify, I have a simple name as a string pulled from another source, eg. "ConflictException". I need to be able to throw that specific exception.
string myException = "ConflictException";
I cannot just do a throw new myException
without first casting (or otherwise converting) to an actual Exception() type. I have tried to do a safe cast, but it cannot convert string to Exception.
Thanks for any ideas.
CodePudding user response:
The short answer is: you can't.
You can't because:
- Exceptions in your list might not be loaded in your current app domain, which could make them impossible to load
- Exceptions don't have a consistent constructor signature, making it error prone to create them using reflection. Although most exception types contain a
ctor(string)
, not all of them do.
You can try something like this, but keep in mind that it is error prone:
// Load all exceptions once and map their name to their type
var exceptions = (
from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
where type.IsSubclassOf(typeof(Exception))
where !type.IsAbstract && !type.IsGenericTypeDefinition
group type by type.Name into g
select g)
.ToDictionary(p => p.Key, p => p.First());
// Later on, load a type by its name
string myException = "ConflictException";
Type exceptionType = exceptions[myException];
// Create a new instance, assuming it has a ctor(string)
Exception exception = (Exception)Activator.CreateInstance(
exceptionType, new object[] { "Some message" });
// throw the exception
throw exception;