Exception Handling in WCF(Part-11)

Exception Handling in WCF:

When an exception occurs in WCF service, the service serializes the exception into a SOAP fault and then send it to client.

By default unhandled exception details are not included in SOAP faults.A generic SOAP fault is returned to client.

To understand better on SOAP fault, we can include exception details in SOAP fault in 2 ways.

  • Enabling IncludeExceptionDetailInFaults setting in app.config to True.
  • Enabling IncludeExceptionDetailInFaults settings to True in code.

we will take an example to understand it better.

We have created a calculator service with one method: Divide.

ICalculatorService.cs code looks like below snippet.

CalculatorService.cs code looks like below snippet:


We have created a CalculatorServiceHost and added project reference to Calculator Service. The Program.cs looks like below.

namespace CaluclatorServiceHost
class Program
static void Main(string[] args)
using (ServiceHost host = new ServiceHost(typeof(CalculatorService.CalculatorService)))
Console.WriteLine(“Host stated @ ” + DateTime.Now);

Then Lets create a console client to test the service.Create a console application and add service reference to Calculator service. Add a web form and drag and drop 3 text boxes and one button.So in 2 text box we will accept Numerator and Denominator and 3rd text box would show the result on Divide button click. The button click even will look like below snippet.

namespace CalculatorClient
public partial class WebForm1 : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)


Now the service is ready and is working fine. But if you will give zero(0) in 2nd text box and hit Divide you will get error.
So lets handle the exception.
Enabling IncludeExceptionDetailInFaults setting in app.config to True.
This is always preferable.

Then stop the host and restart the host and try divide by zero. In exception details, you will see fault exception and the actual error message.

<strong>Attempted to divide by zero. </strong>Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ServiceModel.FaultException`1[[System.ServiceModel.ExceptionDetail, System.ServiceModel, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089]]: Attempted to divide by zero.
Source Error:

You can do it by adding includeExceptionDetailInFaults settings to code.CalculatorService.cs.



© 2015, www.techkatak.com. All rights reserved.

One thought on “Exception Handling in WCF(Part-11)

  1. Heya i amm for tҺe fiгst tіme hеre. ӏ found
    this board and І find It tгuly usеful & it helped mе out a lot.
    I hope to ǥive something back and aid others likе youu helped

Comments are closed.