C # Cannot capture SerializationException

I had a problem in my program in the part where I am loading a serialized file. I want to succeed if the file cannot be deserialized, but for some reason my program will break and not go into the catch clause. Here is 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 into the Deserialize () line. This is an exception:

 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 of [Serializable] attributes to check this out, but I just want to know why the try clause doesn't work.

+4
source share
3 answers

In the Debug menu, go to Exceptions. You probably have exceptions at the Common Language Runtime Exceptions level for a user who is not processed and thrown.

This will cause the Visual Studio debugger to be broken into all exceptions, even if they are in the try / catch block.

If you press F10 to continue after the debugger hits the breakpoint, you should see it in your catch block.

+3
source

If you want to get a SerializationException, you must get an exception in the Serialization process. With the comment [Serializable] you cannot get a SerializationException. Think about it, you cannot get a Time Out exception without creating a DB connection. So put [Serializable] back and specify the wrong parameter to get a SerializationException.

0
source

Why don't you see the type of exception thrown? Then you will find out which exception you should catch. I assume this is not a SerializationException unless your first catch block catches it.

0
source

All Articles