C# try-catch-else

后端 未结 14 1468
暗喜
暗喜 2020-12-30 19:44

One thing that has bugged me with exception handling coming from Python to C# is that in C# there doesn\'t appear to be any way of specifying an else clause. For example, in

14条回答
  •  温柔的废话
    2020-12-30 20:27

    Sounds like you want to do the second thing only if the first thing succeeded. And maybe catching different classes of exception is not appropriate, for example if both statements could throw the same class of exception.

    try
    {
        reader1 = new StreamReader(path1);
        // if we got this far, path 1 succeded, so try path2
        try
        {
            reader2 = new StreamReader(path2);
    
        }
        catch (OIException ex)
        {
            // Uh oh something went wrong with opening the file2 for reading
            // Nevertheless, have a look at file1. Its fine!
        }
    }
    catch (OIException ex)
    {
        // Uh oh something went wrong with opening the file1 for reading.
        // So I didn't even try to open file2
    }
    

提交回复
热议问题