Exceptions vs. Error codes with Services

Here is an interesting question from the MSDN ArchitectureGeneral forum that I decided to answer.

To throw exceptions or use error codes – that is thequestion…

Since God has not handed down any commandments related tothis I think this is a question of principles. 

We want to choose the option that is

1.      Easy to understand, code and use

2.      Consistent with the intent of the language/technologydesigners and common practice

Let's start with the second principle.

According to the .NET FrameworkClass Library Design Guidelines

“Exceptions are the standardmechanism for reporting errors. Applications and libraries should not usereturn codes to communicate errors. The use of exceptions adds to a consistentframework design and allows error reporting from members, such as constructors,that cannot have a return type. Exceptions also allow programs to handle theerror or terminate as appropriate. The default behavior is to terminate anapplication if it does not handle a thrown exception.”

So in this case you have to come down on the side ofexceptions.

As for principle #1 Ease of use…

Developers must always account for exceptions.  They do notalways have to account for error codes.  Many times in my old COM programmingdays bugs were introduced when developers ignored bad HRESULTS.  (Yes baddevelopers can ignore exceptions as well but the error is more obvious).

WCF provides a mechanism for declaring the kinds of faultsyour application can throw with a fault contract.  Yes, SOAP does not useexceptions per se.  This is because exceptions are a language specificconstruct.  However, most SOAP implementations convert faults into exceptionsfor you.

My vote… Go with exceptions, use faultcontracts… this is goodness.