C# try-catch-else

后端 未结 14 1529
暗喜
暗喜 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

    I have taken the liberty to transform your code a bit to demonstrate a few important points.

    The using construct is used to open the file. If an exception is thrown you will have to remember to close the file even if you don't catch the exception. This can be done using a try { } catch () { } finally { } construct, but the using directive is much better for this. It guarantees that when the scope of the using block ends the variable created inside will be disposed. For a file it means it will be closed.

    By studying the documentation for the StreamReader constructor and ReadLine method you can see which exceptions you may expect to be thrown. You can then catch those you finde appropriate. Note that the documented list of exceptions not always is complete.

    // May throw FileNotFoundException, DirectoryNotFoundException,
    // IOException and more.
    try {
      using (StreamReader streamReader = new StreamReader(path)) {
        try {
          String line;
          // May throw IOException.
          while ((line = streamReader.ReadLine()) != null) {
            // May throw IndexOutOfRangeException.
            Char c = line[30];
            Console.WriteLine(c);
          }
        }
        catch (IOException ex) {
          Console.WriteLine("Error reading file: " + ex.Message);
        }
      }
    }
    catch (FileNotFoundException ex) {
      Console.WriteLine("File does not exists: " + ex.Message);
    }
    catch (DirectoryNotFoundException ex) {
      Console.WriteLine("Invalid path: " + ex.Message);
    }
    catch (IOException ex) {
      Console.WriteLine("Error reading file: " + ex.Message);
    }
    

提交回复
热议问题