The CORRECT Way to Code a Custom Exception Class

There is a lot of advice out there on how to go about building your own custom exception classes.  A lot of these sources are at least partially correct. Some are totally wrong.  Some even advocate abandoning the base System.Exception class altogether, but that’s throwing the baby out with the bathwater, in my opinion.  None that I've seen show how to serialize/deserialize your custom exception class should it have additional data in it's subclass. It’s enough to make one despair of ever finding the “right” way to build an exception class. 

A lot of the confusion around exceptions comes about if you’ve ever actually tried to serialize an exception using an Xml-based serializer.  You are testing the code you write, correct? When attempting to serialize your nice new exception class with something like XmlSerializer, the serializer will simply choke, stating that it can’t serialize any class that has an IDictionary member.  And System.Exception has an IDictionary in it.  Yet every piece of literature coming out of Microsoft says that we should build custom exceptions (sub-typed from Exception, and not ApplicationException) and mark them as [Serializable].  What gives?  Well, there are more serializers in the world than just the XML-based serializers, and that’s when it’s important to serialize exceptions.  The System.Runtime.Serialization.Formatters.Binary.BinaryFormatter, for example, serializes exceptions just fine.

So, how do you derive from Exception correctly, particularly if you’ve got additional information in your custom exception class?  I thought you’d never ask.

     [Serializable]
    public class AuthorizationRequiredException : Exception
    {
        public string ResourceReferenceProperty { get; set; }
 
        public AuthorizationRequiredException()
        {
        }
 
        public AuthorizationRequiredException(string message)
            : base(message)
        {
        }
 
        public AuthorizationRequiredException(string message, Exception inner)
            : base(message, inner)
        {
        }
 
        protected AuthorizationRequiredException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
            ResourceReferenceProperty = info.GetString("ResourceReferenceProperty");
        }
 
        [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            if (info == null)
                throw new ArgumentNullException("info");
            info.AddValue("ResourceReferenceProperty", ResourceReferenceProperty);
            base.GetObjectData(info, context);
        }
 
    }
   And here are the tests that drive it to completion (updated to show better testing methods):
  
     [TestClass]
    public class AuthorizationRequiredExceptionTests
    {
        [TestMethod]
        public void AuthorizationRequiredException_default_ctor()
        {
            // Arrange
            const string expectedMessage = "Exception of type 'MyApp.Exceptions.AuthorizationRequiredException' was thrown.";
 
            // Act
            var sut = new AuthorizationRequiredException();
 
            // Assert
            Assert.IsNull(sut.ResourceReferenceProperty);
            Assert.IsNull(sut.InnerException);
            Assert.AreEqual(expectedMessage, sut.Message);
        }
 
        [TestMethod]
        public void AuthorizationRequiredException_ctor_string()
        {
            // Arrange
            const string expectedMessage = "message";
 
            // Act
            var sut = new AuthorizationRequiredException(expectedMessage);
 
            // Assert
            Assert.IsNull(sut.ResourceReferenceProperty);
            Assert.IsNull(sut.InnerException);
            Assert.AreEqual(expectedMessage, sut.Message);
        }
 
        [TestMethod]
        public void AuthorizationRequiredException_ctor_string_ex()
        {
            // Arrange
            const string expectedMessage = "message";
            var innerEx = new Exception("foo");
 
            // Act
            var sut = new AuthorizationRequiredException(expectedMessage, innerEx);
 
            // Assert
            Assert.IsNull(sut.ResourceReferenceProperty);
            Assert.AreEqual(innerEx, sut.InnerException);
            Assert.AreEqual(expectedMessage, sut.Message);
        }
 
        [TestMethod]
        public void AuthorizationRequiredException_serialization_deserialization_test()
        {
            // Arrange
            var innerEx = new Exception("foo");
            var originalException = new AuthorizationRequiredException("message", innerEx) { ResourceReferenceProperty = "MyReferenceProperty" };
            var buffer = new byte[4096];
            var ms = new MemoryStream(buffer);
            var ms2 = new MemoryStream(buffer);
            var formatter = new BinaryFormatter();
 
            // Act
            formatter.Serialize(ms, originalException);
            var deserializedException = (AuthorizationRequiredException)formatter.Deserialize(ms2);
 
            // Assert
            Assert.AreEqual(originalException.ResourceReferenceProperty, deserializedException.ResourceReferenceProperty);
            Assert.AreEqual(originalException.InnerException.Message, deserializedException.InnerException.Message);
            Assert.AreEqual(originalException.Message, deserializedException.Message);
        }
 
        [TestMethod]
        [ExpectedException(typeof(ArgumentNullException))]
        public void AuthorizationRequiredException_GetObjectData_throws_exception_when_info_null()
        {
            // Arrange
            var sut = new AuthorizationRequiredException("message") { ResourceReferenceProperty = "MyReferenceProperty" };
 
            // Act
            // ReSharper disable AssignNullToNotNullAttribute
            sut.GetObjectData(null, new StreamingContext());
            // ReSharper restore AssignNullToNotNullAttribute
 
            // Assert
            // [ExpectedException(typeof(ArgumentNullException))]
        }
    }
  

If you use this code as a template for creating your custom exceptions, you won’t go too far wrong, I think.

As far as XML-based serializers goes, I hope that the Base Class Library team will take some time and just fix the "chokes on IDictionary" issue.  Frankly, it's quite embarrassing.