serialization – C# Can’t catch SerializationException – Education Career Blog

I’m having an issue in my program in the part that I’m loading a serialized file. I want to fail nicely if the file can’t be deserialzed, but for some reason, my program will break rather than go into the catch clause. Here’s my code

using (FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open))
                {
                    try
                    {
                        BinaryFormatter bf = new BinaryFormatter();
                        document = (Document)bf.Deserialize(fs);
                    }
                    catch (SerializationException se)
                    {
                        MessageBox.Show("Error opening this file due to serialization", se.Source);
                    }
                    catch (Exception se)
                    {
                        MessageBox.Show("Error opening this file due to serialization", se.Source);
                    }
                }

Running this causes the program to break on the Deserialize() line. This is the exception that it throws:

Type 'Source' in Assembly 'DocumentDesigner, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

I know how to fix the exception because I commented out a couple Serializable attributes to test this, but I just want to know why the try clause isn’t working.

,

In the Debug menu, go to Exceptions. You probably have Common Language Runtime Exceptions checked for both User Unhandled and Thrown.

This will cause the Visual Studio debugger to break on all exceptions, even if they are in a try/catch block.

If you hit F10 to continue after the debugger hits the breakpoint, you should see it step into your catch block.

,

If you want to get SerializationException, you must get an exception while Serialization process. With commenting Serializable you cant get an SerializationException. Think like this, you cant get Time Out Exception without creating DB Connection. So put Serializable back, and give wrong parameter to get SerializationException.

,

Why don’t you look at the type of the exception that is thrown? Then you’ll know what exception you need to catch. I’m guessing it’s not SerializationException if your first catch block doesn’t catch it.

Leave a Comment