0

I use following code to read data from XML

var temp = default(T);
var serializer = new XmlSerializer(typeof(T));

try
{
    TextReader textReader = new StreamReader(fileName);
    temp = (T)serializer.Deserialize(textReader);
}
catch (InvalidOperationException ioe)
{
    throw;          
}

I know that rethorow it is redundant part, but I wanted to throw it in controled way. I want to use this place to show the user that some XML file has been corupted (ie tag was not closed). Everything works fine until I don't leave the class and I want to catch this exception from the class which request this data. It seems that the exception is missinig and bypassed somehow, and application jump into diffrent method suddenly. Why I cannot catch this exception? I even create my own exception, but the result was the same - it seems that it just not leave original class and cause some application jump.

h__
  • 761
  • 3
  • 12
  • 41

3 Answers3

1

xml deserialization exceptions work just like any other exceptions - there are no surprises (other than it is even more important than usual to check the .InnerExceptions (recursively), because all the interesting information is nested a few exceptions down).

Is this perhaps simply that you are catching the wrong kind of exception? For example, there is no guarantee it is an InvalidOperationException. As long as the calling method has a try with a catch(Exception ex), it should catch any exception that happens during deserialization.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

I found the reason. Method which throw that exception was called by static class constructor. And it was why exception wasn't thrown up. Static constructors are called on the begining and they just don't throw exceptions (do they?). I changed original code by extracting method from xonstructor and by calling it manualy - now I can catch exception in above layer.

h__
  • 761
  • 3
  • 12
  • 41
0

you can use XSD to validate that, there is the only way dynamic that i know to make this kind of validation, this Link could help

renefc3
  • 339
  • 4
  • 17