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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With