C# try-catch-else

后端 未结 14 1523
暗喜
暗喜 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:16

    Catch a specific class of exceptions

    try
    {
        reader = new StreamReader(path);
        string line = reader.ReadLine();
        char character = line[30];
    }
    catch (IOException ex)
    {
        // Uh oh something went wrong with I/O
    }
    catch (Exception ex)
    {
        // Uh oh something else went wrong
        throw; // unless you're very sure what you're doing here.
    }
    

    The second catch is optional, of course. And since you don't know what happened, swallowing this most general exception is very dangerous.

提交回复
热议问题