C# Can't catch SerializationException

你离开我真会死。 提交于 2019-12-21 17:32:23

问题


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.


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/3988422/c-sharp-cant-catch-serializationexception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!