C# try-catch-else

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

    After seeing the other suggested solutions, here is my approach:

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

    Of course, doing this makes sense only if you are interested in any exceptions thrown by opening the file stream (as an example here) apart from all other exceptions in the application. At some higher level of the application, you then get to handle your MyOpeningFileStreamException as you see fit.

    Because of unchecked exceptions, you can never be 100% certain that catching only IOException out of the entire code block will be enough -- the StreamReader can decide to throw some other type of exception too, now or in the future.

提交回复
热议问题