When are custom Exception classes most-valuable?
Are there cases when they should or should not be used? What are the benefits?
Related questions:
When are custom Exception classes most-valuable?
Are there cases when they should or should not be used? What are the benefits?
Related questions:
As Wheelie said, look first for an appropriate framework exception, and only use exceptions (especially custom exceptions) where you really plan to catch them.
I use a custom exception class that contains a UserMessage property, so that I can propagate the problem in plain language to the user when possible.
If you're using .NET, check out Designing Custom Exceptions. Interestingly, the documentation has changed its recommendation on the use of ApplicationException:
I wrote a blog entry a while back about when to throw different types of exceptions, and when to create new exception types. It's not that long but is probably too long to paste here so excuse me for just linking. It should cover your question about why different exception types exist, and how to know whether you need to create a custom one.
Questions to ask yourself:
throw
ing things?Precepts:
catch()
clause).I think the simple answer is "Create a custom exception when no existing exception adequetely expresses the exceptional situation."
I also have a second rule that I apply: "Only create a custom exception if you expect a developer to be able to handle the exception." There is no point in creating a new exception if you don't consider the exception a recoverable condition. It is more effectient to throw InvalidOperationException in that context.
EDIT: Ended up writing a blog post on this subject: http://blogs.msdn.com/jaredpar/archive/2008/10/20/custom-exceptions-when-should-you-create-them.aspx
When you need to distinguish one exception from the others somehow. That's it, really. Of course, you could create an exception class that takes an enum to distinguish its cause, also.
This is really easy to see when you want to pass extra information with the exception. The only reason to pass that information is if you want to be able to get that information later, and so you'll want to know the type so you can retrieve the information from that type and not others.
In C++, and perhaps some other languages, you might also typedef an exception. This would allow for type distinguishing, and possibly future conversion to a custom class.
My main reason for using custom exceptions would be encapsulation with multiple providers: having a SqlException leak out of a SqlDataAccess layer, and a SocketException out of a NetworkDataAccess layer makes calling code dependent on the particulars of your implementation. Better to wrap them into a DataAccessException or something.