How can I create a new exception class and throw it away

In C # .NET, how can I create a new exception class and throw it in Runtime. I need to create a runtime exception class name based on the string I get as input. It seems I should use Reflection.emit, but I don't know how to do this.

+4
source share
2 answers

While I do not understand the purpose of creating an exception type using reflection, creating an exception type is no different from creating any other type:

// Build an assembly ...
var appDomain = Thread.GetDomain();
var assemblyName = new AssemblyName("MyAssembly");
var assemblyBuilder = appDomain.DefineDynamicAssembly(
  assemblyName,
  AssemblyBuilderAccess.Run
);

// ... with a module ...
var moduleBuilder = assemblyBuilder.DefineDynamicModule("MyModule");

// ... containing a class.
var typeBuilder = moduleBuilder.DefineType(
  "MyException",
  TypeAttributes.Class,     // A class ...
  typeof(Exception)         // ... deriving from Exception
);
var exceptionType = typeBuilder.CreateType();

// Create and throw exception.
var exception = (Exception) Activator.CreateInstance(exceptionType);
throw exception;
+3
source

All Articles