views:

80

answers:

5

Sometimes I dont know witch type of exception should I throw. So I usually throw Exception(). Is there some nice article about this?

+2  A: 

The problem with throwing a generic exception is that it restricts the ability of your code further up the stack to handle it properly (i.e. best practice is to trap the most specific exception possible before falling back, and to only capture what you can handle).

Jeffrey Richter has an excellent section on exception handling (including info on the System.Exception namespace) in CLR via C#

Bob Palmer
+1 Richter is an excellent resource for this.
Steve Haigh
+1  A: 

Well, the one thing you shouldn't do is throw Exception itself.
Always look for an appropriate subclass.

I don't know of any publication spelling out which exception to throw when, but ArgumentException and InvalidOperationException should take care of most of your cases.

Ask separate questions about separate cases if they come up.

Henk Holterman
Both Richter and Cwalina offer advice on when / what to throw.
Steve Haigh
+1  A: 

If you are not making any attempt to recover from an error, you can just throw an Exception with a string to tell you what went wrong. (Or if you will perform the same action regardless of what error occurred).

Other than making it obvious to a programmer what went wrong by using a new exception name rather than putting it in the Message, and exception can contain data to help you recover from a particular exception.

For example, an ArgumentNullException has a property ParamName, which you should set when you throw the exception. When the caller catches it, he can then look up this property and decide to pass a new value for the argument which caused the error, or can print a relevant error to inform the programmer what went wrong.

It's unfortunate that exceptions are rarely used to their full potential (in many open source APIs and such), and are often simply inserted to inform a programmer what went wrong. There's not much difference between these 2 if you don't plan to read the ParamName property when you catch it. (Many people will not bother, and only catch an Exception anyway).

throw new ArgumentNullException("arg1");
throw new Exception("arg1 is null");

It can be difficult to recover from an error fully, but in some applications though, you might find it desirable to create custom exceptions which can provide all the details you need.

For now, I would just put Exception into the Object browser search in VS, and see what is there already. Their names are pretty self explanatory, so you should be able to pick out something suitable.

Mark H
+2  A: 

"Framework Design Guidelines" by Cwalina and Abrahms covers this topic really well (IMHO).

It is available for free online here, or the book (not free) here (UK) or here(US). Look in the section entitled Design Guidelines for Exceptions.

Steve Haigh
+1  A: 
supercat