我完全接受这本质上是重复问题 Catching custom exception in c# 这个问题已经解决,所以我希望在遇到同样问题时改写一下。
我有一堂课可以总结一下。
[Serializable()]
public class DataFile : ISerializable
{
public DataFile()
{
// Data structures
}
public DataFile(SerializationInfo info, StreamingContext ctxt) : this()
{
if(true)
{
throw new VersionNotFoundException();
}
// Load data
}
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
// Save data
}
}
在MainForm中,我有一个方法包含与之等效的代码。
private DataFile Data;
private string CurrentFile = "C:\myfile.xyz";
private void LoadData()
{
try
{
using (Stream stream = File.Open(CurrentFile, FileMode.Open))
Data = (DataFile)new BinaryFormatter().Deserialize(stream);
}
catch (VersionNotFoundException e)
{
// never gets here
}
catch (Exception e)
{
// VersionNotFoundException gets caught here as an inner exception
}
}
我的问题
为什么VersionNotFoundException不会在“ catch(VersionNotFoundException e)”部分中被捕获(我没有将其添加到异常堆栈的顶部)吗?我在做什么错,该如何解决?为什么/如何做出“内部”异常以及如何阻止它?