Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Organizing Custom Exceptions in C#

I am creating a C# application and am trying to take advantage of custom exceptions when appropriate. I've looked at other questions here and at the MSDN design guidelines but didn't come across anything as specific as what I'm wondering here.

What is the best practice for how to organize custom exceptions?

For example, I have a class Disk that throws an InvalidDiskException. Disk is the only class that throws this exception.

Currently, I have the exception nested in the Disk.cs file as follows:

Disk.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OrganizingExceptionsInCSharp
{
    class Disk
    {
        [Serializable]
        public class InvalidDiskException : Exception
        {
            public InvalidDiskException() { }
            public InvalidDiskException(string message) : base(message) { }
            public InvalidDiskException(string message, Exception innerException) : base(message, innerException) { }
        }

        //
        // Code that throws the exception.
        //
    }
}

Should the exception be defined at the same level as Disk (ie. not nested within)? Should the exception be nested within Disk but kept it's own partial file? Might there be other, better options? Please let me know if there are other considerations I haven't thought of.

like image 220
Kyle Tolle Avatar asked Oct 08 '12 21:10

Kyle Tolle


1 Answers

I'd define my custom exceptions in {MyNamespace}.Exceptions

like image 119
Mauro Sampietro Avatar answered Sep 18 '22 21:09

Mauro Sampietro