damichab
damichab

Reputation: 189

How to throw and catch an exception

I fully accept that this is essentially a repeat of question of Catching custom exception in c# That question is closed, so I hope to rephrase it as I am having the same problem.

I have a class that can be summarised thus..

[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 
    }
}

In my MainForm, I have a method that constains code equivilant to..

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

My question(s)

Why would the VersionNotFoundException not get caught in the "catch (VersionNotFoundException e)" section (have I not added it to the top of the exception stack)? What am I doing wrong and how do I fix it? Why/how am I making an 'inner' exception and how do I stop it?

Upvotes: 0

Views: 95

Answers (1)

TheGeneral
TheGeneral

Reputation: 81483

I was scratching my head with this and completely missed the comment.

// VersionNotFoundException gets caught here as an inner exception

You cannot catch inner exceptions like this, however you can use when in C#6 or later

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

Demo here

Upvotes: 3

Related Questions