Asking how many statements you should put in a try
is like asking how many statements you should put in an if
, or a for
loop. Why did you never ask "how many statements should I put in an if
statement?"? Because you understand what an if
statement is, and that the number of statements in it doesn't matter*. What matters is "what statements make sense when put in there?" So instead, you'd probably asked "What do I put inside an if
?".
The above paragraph stopped making sense after OP's edit of the question, but that's fine!
What you seem to not understand is why we sometimes put many lines of code inside a try
. Well, one example of this is when you read a JSON file. You'd do something like this (very rough example, for illustration purposes only):
try {
string json = ReadFile();
MyObject obj = ParseJSON(json);
DoSomethingWithMyObject(obj);
} catch (FileNotFoundException ex) {
ShowErrorToUser("File Not Found");
} catch (JsonReaderException ex) {
ShowErrorToUser("Invalid File");
}
ReadFile
might throw a FileNotFoundException
and ParseJSON
might throw a JsonReaderException
. You can't really separate these three lines into 2 try
s:
string json;
MyObject obj;
try {
json = ReadFile();
} catch (FileNotFoundException ex) {
ShowErrorToUser("File Not Found");
}
try {
obj = ParseJSON(json);
} catch (JsonReaderException ex) {
ShowErrorToUser("Invalid File");
}
DoSomethingWithMyObject(obj);
Why? Because definite assignment rules says that json
and obj
are not definitely assigned when they are used! You see, even when ReadFile
fails, ParseJSON
will still execute, but json
will not have a value if ReadFile
fails!
If you say "well, I can just give json
a default value then!", that's true, but it doesn't always make sense to do so. Sometimes one part of your method just can't run if another part of it throws an exception. This is a sign that the two parts should be in the same try
block#.
*Well, it does matter if you're talking about style...
#Obviously, if your method can't handle the exception, then there should not be a try
block at all.