C# try-catch-else

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

    Catch more specific exceptions.

    try {
       reader = new StreamReader(path);
       string line = reader.ReadLine();
       char character = line[30];
    }
    catch(FileNotFoundException e) {
       // thrown by StreamReader constructor
    }
    catch(DirectoryNotFoundException e) {
       // thrown by StreamReader constructor
    }
    catch(IOException e) {
       // some other fatal IO error occured
    }
    

    Further, in general, handle the most specific exception possible and avoid handling the base System.Exception.

    0 讨论(0)
  • 2020-12-30 20:14

    You can do this:

    try
    {
        reader = new StreamReader(path);
    }
    catch (Exception)
    {
        // Uh oh something went wrong with opening the file for reading
    }
    
    string line = reader.ReadLine();
    char character = line[30];
    

    But of course, you will have to set reader into a correct state or return out of the method.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2020-12-30 20:17

    You can nest your try statements, too

    0 讨论(0)
  • 2020-12-30 20:19

    Exceptions are used differently in .NET; they are for exceptional conditions only.

    In fact, you should not catch an exception unless you know what it means, and can actually do something about it.

    0 讨论(0)
提交回复
热议问题