title: Catching a custom Exception thrown by a WebMethod on ASP.NET WebService
body: <p>I have a classical asp.net web service (asmx) and a web method in it. I need to throw a custom exception for some case in my web method, and I need to catch that specific custom exception where I call the web service method.</p>
  
  <pre><code>[WebService(Namespace = "http://tempuri.org/")]
  [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  public class WebService : System.Web.Services.WebService
  {
      [WebMethod]
      public HelloWorldOutput HelloWorld(HelloWorldInput input)
      {
          try
          {
              // My Code
              return new HelloWorldOutput();
          }
          catch (Exception ex)
          {
              throw new HelloWorldException("Hello World Exception", ex);
          }
      }
  }
  </code></pre>
  
  <p>Input, output and exception classes as a sample:</p>
  
  <pre><code>public class HelloWorldInput { }
  public class HelloWorldOutput { }    
  
  [Serializable]
  public class HelloWorldException : Exception
  {
      public HelloWorldException() { }
      public HelloWorldException(string message) : base(message) { }
      public HelloWorldException(string message, Exception inner) 
          : base(message, inner) { }
      protected HelloWorldException(
        System.Runtime.Serialization.SerializationInfo info,
        System.Runtime.Serialization.StreamingContext context)
          : base(info, context) { }
  }
  </code></pre>
  
  <p>In the client side, I need:</p>
  
  <pre><code>public static void Main()
  {
      WebService service = new WebService();
      try
      {
          service.HelloWorld(new HelloWorldInput());
      }
      catch (HelloWorldException ex)
      {
          // Do sth with HelloWorldException
      }
      catch (Exception ex)
      {
          // Do sth with Exception
      }
  }
  </code></pre>
  
  <p>However, I cannot do that because when I add the web service reference on the client, I have service class, input and output classes, but I do not have custom exception class.</p>
  
  <p>Also another problem is that, I have also problems with serializing Exception class (because of Exception.Data property implements IDictionary interface)</p>
  
  <p>Is there a way to do this in my way, or am I in a completely wrong way, or is there something I miss about fundamentals of web services?</p>
  
  <p>Thanks.</p>