title: c# exception handling, practical example. How would you do it?
body: <p>I'm trying to get better at handling exceptions but I feel like my code gets very ugly, unreadable and cluttered when I try my best to catch them. I would love to see how other people approach this by giving a practical example and compare solutions.</p>
  
  <p>My example method downloads data from an URL and tries to serialize it into a given type, then return an instance populated with the data.</p>
  
  <p>First, without any exception-handling at all:</p>
  
  <pre><code>    private static T LoadAndSerialize&lt;T&gt;(string url)
      {            
          var uri = new Uri(url);
          var request = WebRequest.Create(uri);
          var response = request.GetResponse();
          var stream = response.GetResponseStream();
  
          var result = Activator.CreateInstance&lt;T&gt;();
          var serializer = new DataContractJsonSerializer(result.GetType());
          return (T)serializer.ReadObject(stream);            
      }
  </code></pre>
  
  <p>I feel like the method is fairly readable like this. I know there are a few unnecessary steps in the method (like WebRequest.Create() can take a string, and I could chain methods without giving them variables) there but I will leave it like this to better compare against the version with exception-handling.</p>
  
  <p>This is an first attempt to handle everything that could go wrong:</p>
  
  <pre><code>    private static T LoadAndSerialize&lt;T&gt;(string url)
      {
          Uri uri;
          WebRequest request;
          WebResponse response;
          Stream stream;
          T instance;
          DataContractJsonSerializer serializer;
  
          try
          {
              uri = new Uri(url);
          }
          catch (Exception e)
          {
              throw new Exception("LoadAndSerialize : Parameter 'url' is malformed or missing.", e);
          }
  
          try
          {
              request = WebRequest.Create(uri);
          }
          catch (Exception e)
          {
              throw new Exception("LoadAndSerialize : Unable to create WebRequest.", e);
          }
  
          try
          {
              response = request.GetResponse();
          }
          catch (Exception e)
          {
              throw new Exception(string.Format("LoadAndSerialize : Error while getting response from host '{0}'.", uri.Host), e);
          }
  
          if (response == null) throw new Exception(string.Format("LoadAndSerialize : No response from host '{0}'.", uri.Host));
  
          try
          {
              stream = response.GetResponseStream();
          }
          catch (Exception e)
          {
              throw new Exception("LoadAndSerialize : Unable to get stream from response.", e);
          }
  
          if (stream == null) throw new Exception("LoadAndSerialize : Unable to get a stream from response.");
  
          try
          {
              instance = Activator.CreateInstance&lt;T&gt;();
          }
          catch (Exception e)
          {
              throw new Exception(string.Format("LoadAndSerialize : Unable to create and instance of '{0}' (no parameterless constructor?).", typeof(T).Name), e);
          }
  
          try
          {
              serializer = new DataContractJsonSerializer(instance.GetType());
          }
          catch (Exception e)
          {
  
              throw new Exception(string.Format("LoadAndSerialize : Unable to create serializer for '{0}' (databinding issues?).", typeof(T).Name), e);
          }
  
  
          try
          {
              instance = (T)serializer.ReadObject(stream);
          }
          catch (Exception e)
          {
              throw new Exception(string.Format("LoadAndSerialize : Unable to serialize stream into '{0}'.", typeof(T).Name), e);                   
          }
  
          return instance;
      }
  </code></pre>
  
  <p>The problem here is that while everything that could possibly go wrong will be caught and given a somewhat meaningful exception, it is a clutter-fest of significant proportions.</p>
  
  <p>So, what if I chain the catching instead. My next attempt is this:</p>
  
  <pre><code>    private static T LoadAndSerialize&lt;T&gt;(string url)
      {
          try
          {
              var uri = new Uri(url);
              var request = WebRequest.Create(uri);
              var response = request.GetResponse();
              var stream = response.GetResponseStream();
              var serializer = new DataContractJsonSerializer(typeof(T));
              return (T)serializer.ReadObject(stream);
          }
          catch (ArgumentNullException e)
          {
              throw new Exception("LoadAndSerialize : Parameter 'url' cannot be null.", e);
          }             
          catch (UriFormatException e)
          {
              throw new Exception("LoadAndSerialize : Parameter 'url' is malformed.", e);
          }
          catch (NotSupportedException e)
          {
              throw new Exception("LoadAndSerialize : Unable to create WebRequest or get response stream, operation not supported.", e);
          }
          catch (System.Security.SecurityException e)
          {
              throw new Exception("LoadAndSerialize : Unable to create WebRequest, operation was prohibited.", e);
          }
          catch (NotImplementedException e)
          {
              throw new Exception("LoadAndSerialize : Unable to get response from WebRequest, method not implemented?!.", e);
          }
          catch(NullReferenceException e)
          {
              throw new Exception("LoadAndSerialize : Response or stream was empty.", e);
          }
      }
  </code></pre>
  
  <p>While it certainly is easier on the eyes, I am leaning heavily the intellisense here to provide all exceptions that can possibly be thrown from a method or class. I don't feel confident that this documentation is 100% accurate, and would be even more skeptical if some of the methods came from an assembly outside the .net framework. As an example the DataContractJsonSerializer show no exceptions on the intellisense. Does this mean the constructor will never fail? Can I be sure?</p>
  
  <p>Other issues with this is that some of the methods throw the same exception, which makes the error harder to describe (this or this or this went wrong) and so is less useful to the user / debugger.</p>
  
  <p>A third option would be to ignore all exceptions apart from the ones that would allow me to take an action like retrying the connection. If the url is null then the url is null, the only benefit from catching that is a little bit more verbose error message.</p>
  
  <p>I would love to see your thoughts and/or implementations!</p>