Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use a new exception type

What are the guidelines for when to create a new exception type instead of using one of the built-in exceptions in .Net?

The problem that got me thinking is this. I have a WCF service, which is a basic input-output service. If the service is unable to create an output, because the input is invalid, I want to throw an exception, but which one?

Right now I'm just throwing system.Exception, but this doesn't feel right to me, I don't know why, it just feels wrong. One thing that bugs me, if I test it with a unit test and I expect the system.Exception to be thrown. The exception could as well be thrown by the framework or other code and not by the code I excepted to throw. The test would then pass, as I get the expected exception, but it should have failed.

What do you recommend?

like image 203
Karsten Avatar asked Oct 13 '08 12:10

Karsten


1 Answers

Avoid throwing System.Exception or System.ApplicationException yourself, as they are too general.

For WCF services there are Fault Contracts - a generic exception that you can tell subscibers to handle.

Flag the interface with:

[FaultContract( typeof( LogInFault ) )]
void LogIn( string userName, string password, bool auditLogin );

Then if there is an exception you can throw this specific fault:

throw new FaultException<LogInFault>( new LogInFault(), "message" );

Use the [DataContract] serialisation on your fault - this saves you from having to handle all the serialisation stuff exceptions normally require.

like image 88
Keith Avatar answered Oct 14 '22 19:10

Keith