Question

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

Was it helpful?

Solution

While I do not understand the purpose of creating an exception type using reflection emit, creating an exception type is no different than 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;

OTHER TIPS

I think you can look into this article for exception : http://blog.gurock.com/articles/creating-custom-exceptions-in-dotnet/

And to this thread to solve the definition issue at runtime : Creating a class for an interface at runtime, in C#

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top