views:

115

answers:

6
+2  Q: 

.net exceptions

When should I create my own custom exception class rather than using a one provided by .Net?

Which base exception class should I derive from and why?

+1  A: 

One reason to create your own exception is to be able to isolate them for catching. For example:

try {
// do stuff
} catch (MyCustomException e) {
// handle this known exception
}

All other exceptions can bubble up and be handled at another level.

Larsenal
A: 

I'd create my own excpetion class if i wanted to add other properties to it such as variables, location, user name, num returned records etc.

essentially i'd create a class that would narrow down what the error was and how to re-create it.

edit

oh and you could add validation errors to an exception class that can be passed to the front end to show the errors.

griegs
+2  A: 

The goal of exception handling should be to create a clear understanding of what went wrong. Therefore, you should define your own exception any time the provided exceptions do not provide that clear understanding.

For example, I'm writing an application which converts Arabic Numerals to Roman Numerals. One of the constraints in this application is that Roman Numerals must fall within the range 0 < x < 4000.

private string ToRoman(int number)
{
    if (number > 0 && number < 4000)
    {
        //ConvertHere
    }
    else
    {
        //Custom exception used for readability purposes.
        throw new NumeralOutOfRangeException();
    }
}

As for which base class to use, Microsoft recommends that user defined exceptions subclass Exception. (http://msdn.microsoft.com/en-us/library/seyhszts.aspx)

RevolXadda
How does "ArgumentOutOfRangeException" not cover your case? It's an argument, and it's out of range. Why do you care if it's a "numeral" or not?
Mystere Man
You're right. ArgumentOutOfRangeException definitely covers this case. I was just looking for a quick, simple example, and this was the first one that came to mind.
RevolXadda
+5  A: 

Why create your own exception?

You create your own exception so that when you throw them, you can have specific catches and hence differentiate them from system thrown (unhandled) exceptions.

What class should you derive it from?

Earlier, it was standard practice for custom exceptions to be derived from ApplicationException class but over time, MS recommendations have changed encouraging developers to derive from System.Exception itself rather than ApplicationException

InSane
Do you have a link about that Microsoft recommendation about ApplicationException versus Exception? I'm interested to read that.
Pierre-Alain Vigeant
is there any specific reason why derive from System.Excption and not from ApplicationException?
Ruby
@Pierre-Alain Vigeant and Ruby - Have a look at the discussion around here http://blogs.msdn.com/b/kcwalina/archive/2006/06/23/644822.aspx and http://blogs.msdn.com/b/brada/archive/2004/03/25/96251.aspx...these might help clarify why.
InSane
Also, the MSDN link for ApplicationException http://msdn.microsoft.com/en-us/library/system.applicationexception(VS.90).aspx and the Best Practives for handling exceptions http://msdn.microsoft.com/en-us/library/seyhszts(v=VS.90).aspx are part of the official MS recommendations
InSane
+1  A: 

This may seem a bit obvious but you should create an exception when no built in exceptions make sense. Typically I will define a base exception for a library I am working on.

public class MyLibraryException : Exception
{
    // .....
}

Then I will create an exception for situations that may arise when using the library.

public class SomethingHorribleException : MyLibraryException 
{
    // .....
}

Then the client can always know that my library will throw something that inherits MyLibraryException.

ChaosPandion
A: 

The answers so far all look good, but I would also add:

To hide implementation details that might otherwise be exposed because you need to handle those exceptions.

E.g. You don't want your UI to catch SQLException. You should throw your own exceptions out of your data access code and let your UI deal with those. If you changed to a non database provider for data storage (e.g. XML, file system, etc), you would not need to change your UI code.

However, I would only do that if I was handling them in my UI code explicitly.

Jim Leonardo