C# 无法捕获 SerializationException [英] C# Can't catch SerializationException

查看:38
本文介绍了C# 无法捕获 SerializationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序在加载序列化文件的部分出现问题.如果文件不能反序列化,我想很好地失败,但由于某种原因,我的程序将中断而不是进入 catch 子句.这是我的代码

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);
                    }
                }

运行这个会导致程序在 Deserialize() 行中断.这是它抛出的异常:

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.

我知道如何修复异常,因为我注释掉了几个 [Serializable] 属性来测试这个,但我只想知道为什么 try 子句不起作用.

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.

这将导致 Visual Studio 调试器中断所有异常,即使它们位于 try/catch 块中.

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

如果在调试器命中断点后按 F10 继续,您应该会看到它进入您的 catch 块.

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

这篇关于C# 无法捕获 SerializationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆