Differences between your example and similar code in which there is only one, outer, catch:
1) If the inner block throws, then the message is printed before calling Close()
. This might be significant if Close()
also contains logging.
2) If an inner exception is thrown and caught, and then in the finally block Close()
also throws, you get two exceptions and you handle two exceptions. With only one catch block, if Close()
throws then what happens next might depend on language, but you won't get two error messages printed. I'd expect the second exception to replace the first one, but I don't swear that's what happens in all languages with finally
, or even all languages I've used...
3) //Show error message
is just a comment, it does nothing. It may be the intention of the author that you'd show a different error message in the two different cases. The inner one would say, "read failed", and the outer one would say, "cannot open file". Or something like that. To achieve that with only one catch block, you could set and check a flag indicating progress (which probably doesn't make the code any simpler than two catch blocks), or you could rely on the exception itself to contain the appropriate error message (in which case good luck with integrating your localization framework with exception-throwing functions in built-in or third-party libraries).
Note that even if you only have one catch, you still need two tries because of the finally
. This is no good:
try {
TextReader tr = new StreamReader("filename");
string content = tr.ReadToEnd();
} catch(Exception ex) {
// show error message
} finally {
tr.Close();
}
Because by the looks of this language, tr
will not be in scope in the finally
block, so we can't close it there. We have to close it inside the block that deals with creating it. It may be that we could deal with it like this:
TextReader tr = null;
try {
tr = new StreamReader("filename");
string content = tr.ReadToEnd();
} catch(Exception ex) {
// show error message
} finally {
if (tr != null) {
tr.Close();
}
}
But that doesn't really simplify things much compared with the original code, we still have differences 2-3 to contend with, and now we don't handle exceptions from Close()
at all. So for many purposes the original code with multiple try/catch was better.