Search code examples
wcfexceptionfaultfaultexception

WCF - Throw an Exception or FaultException?


What's more efficient? Throwing an exception or throwing a fault... the way I see it is that there's 2 scenarios:

  1. An exception occurred and is caught, do you throw that existing Exception or create a new FaultException and throw that?

  2. Your own logic (such as username can't be blank) needs to throw an error either as an Exception or FaultException. Which do you choose?

Basically, which way is the best practice way? I ask because I remember reading somewhere about WCF boxing or unboxing exceptions and it costing additional resources and such like... so I guess also, which is the more efficient way?


Solution

  • Coming from a WSDL Contract Perspective, each operation can can have at most one response. However, you can define multiple fault contracts, which basically tells a client "Expect either a response defined by DataContractX, or a fault response defined by FaultContractY or FaultContractZ."

    Using FaultExceptions allows you finer control over how your WSDL is represented (or in writing a compliant service against an already defined WSDL).

    If you are truly attempting to achieve interoperability and are fully leveraging wsdl and soap to achieve this you will need to use FaultExceptions. If you are using WCF in a .NET only interaction you can use Exceptions or Fault Exceptions, I don't think the performance difference will be significant (Communicating over the network is order of magnitudes more significant than the WCF runtime wrapping Exceptions into a Generic Fault for transmission over the wire).