Mark Wilson I am the creator of TopXML. I am available for international and local (Australia) contracts. I am a Solution Architect/Business Analyst. I have worked in IT in several countries (NZ, Australia, South Africa, UK) building and training teams for government and very large non-governmental organizations. I am ex-Microsoft Consulting Services. I wrote the first book on Microsoft XML published in 2000 called XML Programming with VB and ASP. Most recently I have been building tools for the SEO industry. Ask me for a 37 point SEO health-checkup for your website.
The XmlSerializer throws exceptions to indicate all sorts of
problems. In most cases an exception handler will catch a System.InvalidOperationException
thrown in Serialize() or Deserialize(), which makes the StackTrace property
useless because it does not offer any more insight into the root cause of the
exception. To make matters worse, the exception’s Message property only yields
very generic information. If we are trying to serialize an undeclared type for
example the Serialize() method would throw an exception with the following
message:
There was an error generating the XML document. This message is annoying at best, because we already figured that
much when we saw an exception and doesn’t help us troubleshooting the problem.
The trick to get to the “real information” about the problem is to examine the
exception’s InnerException property, which contains very detailed
information about the problem and where it occurred.
The InnerException’s message is usually very descriptive,
pinpoints the problem and, in many cases, even offers a possible solution. When
we are trying to serialize an undeclared type the InnerExcpetion reads
something like this: The type XmlSerializationApp.XmlCar was not expected. Use the
XmlInclude or SoapInclude attribute to specify types that are not known
statically.
The following listing demonstrates how to set up the exception
handler and how to access the InnerException property.
4
Listing 9.9 Handling an
Exception from the XmlSerializer and displaying the embedded information
using System;
public static ParkingLot DeserializeParkingLot( XmlReader reader
)
{
ParkingLot lot = null;
try
{
XmlSerializer ser =
new XmlSerializer( typeof(ParkingLot));
lot = (ParkingLot)
ser.Deserialize( reader );
}
catch( Exception ex
) |#1
{ |
DumpException( ex
); |
} |
return lot;
}
public static void DumpException( Exception ex )
{
WriteExceptionInfo( ex
); |#2
if( null !=
ex.InnerException ) |
{ |
WriteExceptionInfo(
ex.InnerException ); |
}
}
public static void WriteExceptionInfo( Exception ex )
{
Console.WriteLine(
"--------- Exception Data ---------" ); |#3