.NET/C#: a generic exception class
Posted by jpluimers on 2010/07/28
I want my exceptions to be bound to my business classes.
So you need your own exception class, and are expected to override the 4 constructors of the Exception class.
But I got a bit tired of writing code like this again and again:
using System;
using System.Runtime.Serialization;
namespace bo.Sandbox
{
public class MyException : Exception
{
public MyException()
: base()
{
}
public MyException(string message)
: base(message)
{
}
public MyException(string message, MyException inner)
: base(message, inner)
{
}
public MyException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
}
Searching for Generic Exception Class did not reveal any generic exception classes.
So I wrote this instead:
using System;
using System.Runtime.Serialization;
namespace bo.Sandbox
{
public class Exception<T> : Exception
{
public Exception()
: base()
{
}
public Exception(string message)
: base(message)
{
}
public Exception(string message, Exception inner)
: base(message, inner)
{
}
public Exception(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
}
Now I can raise and catch exceptions like this:
using System;
namespace bo.Sandbox
{
public class My
{
public static void ShowGenericException()
{
try
{
throw new Exception<My>("Oops");
}
catch (Exception<My> ex)
{
Console.WriteLine(ex.ToString());
throw;
}
}
}
}
It will write something like this to the console:
bo.Sandbox.Exception`1[bo.Sandbox.My]: Oops
at bo.Sandbox.My.ShowGenericException() in C:\develop\VS2008\Projects\bo.SandBox.Console\bo.SandBox.Console\Program.cs:line 12
Note however that there is a bug when passing your Exception class as a generic type.
This is a known bug (fixed in Visual Studio 2010), and mentioned on stackoverflow twice.
So: this code will fail under the debugger from Visual Studio 2005 and 2008; you will need to have Visual Studio 2010 to have this example work:
using System;
using System.Runtime.Serialization;
namespace bo.Sandbox
{
public class My
{
static void RunTest<T>()
where T : Exception, new()
{
try
{
throw new T();
}
catch (T ex)
{
Console.WriteLine("Caught passed in exception type");
}
catch (Exception ex)
{
Console.WriteLine("Caught general exception");
}
Console.Read();
}
public static void Main()
{
RunTest<Exception<My>>();
}
}
}
Conclusions:
- Having a generic exception class is neat: it makes throwing and catching a breeze.
- But be careful passing the class itself around as a generic type: under the debugger, this fails under Visual Studio 2008 and 2005.






Leave a comment