title: How to manage XML serialization exceptions for enum
body: <p>I'm using XML serialization to produce a file in a format specific to another application. One of the requirements is that all booleans be represented as 1 or 0. I've looked at some possibilities, including a <a href="https://codereview.stackexchange.com/questions/4829/presenting-a-boolean-as-an-int-for-xmlserialization-in-c">struct</a> to handle this easily and seamlessly. Currently I'm looking into another venue, which is to use an enum.</p>
  
  <pre><code>public enum BoolEnum
  {
      [XmlEnum("0")]
      False = 0,
      [XmlEnum("1")]
      True = 1
  }
  </code></pre>
  
  <p>So far, it works wonderfully, and it's much cleaner. BUT (!) I'm also trying to make the deserialization easy, and I'd just like to be able to handle errors. If I produce an invalid tag:</p>
  
  <pre><code>&lt;invalid&gt;2&lt;/invalid&gt;
  </code></pre>
  
  <p>to be deserialized as BoolEnum, I get an InvalidOperationException inside another InvalidOperationException. How can I catch that exception in an enum?</p>
  
  <hr>
  
  <p>Addendum:</p>
  
  <p>Deserialization function:</p>
  
  <pre><code>static void Deserialize&lt;T&gt;(out T result, string sourcePath) where T : class
  {
      FileStream fileStream = null;
  
      try
      {
          fileStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read);
          XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
          result = xmlSerializer.Deserialize(fileStream) as T;
      }
      finally
      {
          if (fileStream != null)
              fileStream.Close();
      }
  }
  </code></pre>
  
  <p>Deserialized object:</p>
  
  <pre><code>public class Test
  {
      [XmlElement("someboolvalue")
      public BoolEnum SomeBoolValue { get; set; }
  }
  </code></pre>