如何引发和捕获异常

时间:2020-07-10 04:25:09

标签: c# exception

我完全接受这本质上是重复问题 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)”部分中被捕获(我没有将其添加到异常堆栈的顶部)吗?我在做什么错,该如何解决?为什么/如何做出“内部”异常以及如何阻止它?

1 个答案:

答案 0 :(得分:3)

我为此抓挠了头,完全错过了评论。

// VersionNotFoundException gets caught here as an inner exception

您无法捕获此类内部异常,但是可以在C#6或更高版本中使用when

try
{
   
}
catch (Exception e) when (e.InnerException is VersionNotFoundException e2) 
{
   Console.WriteLine(e2.Message);
}
catch (Exception e)
{
  
}

Demo here