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 { getset; }
 
        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.DemandSerializationFormatter = 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(nullnew 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.

Comments (11)

  1. Sure to help enough

  2. Alex says:

    Your constructor tests are pretty bad though. Assert.IsNotNull will always return true, unless the constructor throws an exception. But you're not testing the message or inner exception are as expected.

  3. @Alex, you're right, I am pretty sloppy on the constructor tests. Over the years, I've come to believe that testing base class functionality yields minimal utility, like testing automatic properties, for example.  If I'm overriding any of that base class functionality, however, I'd definitely provide more rigorous tests.  

    However, there is an argument to be made that merely deriving from a base class obligates you to test at least the major parts of the base class to confirm that you haven't (or won't in the future) break base class functionality (in this case Message and InnerException as you state), so I'll update the post to cover those.  Thanks for the remote pair-programming help!

    There is also a ResourceReferenceProperty, so we should probably go ahead and add that into the mix for the constructors to test.

  4. Daniel Bradley says:

    Nice pointers on the serialization aspect.

    The only thing I'd add to your pattern would be to aim to make the custom properties immutable where possible and set the value only via the constructor.

  5. Matt says:

    This is all correct and good and all. But I can't help feeling, this is all worthless boilerplate code that I don't want to have to write or care about.

  6. @Daniel, Good point – no need for exception "properties" to be mutable in my opinion either.

    @Matt, I hear you.  Some of the tests are a bit overkill in my opinion, too, but I do care about whether or not the serialization is working correctly.  That's what I see missing in most custom exception examples.  

    Should writing custom exceptions be easier?  Yeah, I think so, but this is where we are today.  If you have another opinion about a better way to get around all the boilerplate, I'd love to hear it!

  7. What circumstances would require a Serializable Exception? Remoting, I guess? I cannot see it being particularly valuable on it's own, but I'm probably missing something.

  8. Sam Shiles says:

    The tests would also benefit from being split out into several more tests that only contain a single assert. The problem with having three asserts is that if the first one fails, the subsequent ones will not get run.

  9. Kevin says:

    @Michael Burgwin – If an exception has to cross an AppDomain boundary, it requires serialization. Most (with very few exceptions) objects that cross an AppDomain boundary require serialization. Exceptions are a bit of a special case with serialization because you have no control over a thrown exception in regards to how to goes across AppDomains.

    I admit that this blog post didn't really get that point across.

  10. @Kevin: Thanks, that clears it up, and makes a lot of sense. I haven't had to deal with crossing Application Domains very often which is probably why it went above my head.

  11. Michael Kellogg says:

    This is solid.  Saved me an hour of coding and gave me a great reference on best practices for this type of work.  Double kill !  

Skip to main content