Just curious: Why is the syntax for try catch in C# (Java also?) hard coded for multiple statements? Why doesn't the language allow:
int i; string s = DateTime.Now.Seconds % 2 == 1 ? "1" : "not 1"; try i = int.Parse(s); catch i = 0;
The example is for trivial purposes only. I know there's int.TryParse
.
So we can omit curly braces only there is a single statement under if-else or loop. Here in both of the cases, the Line1 is in the if block but Line2 is not in the if block. So if the condition fails, or it satisfies the Line2 will be executed always.
Without a try catch, you run the risk of encountering unhandled exceptions. Try catch statements aren't free in that they come with performance overhead. Like any language feature, try catches can be overused.
One reason to avoid #1 is that it poisons your ability to use exception breakpoints. Normal-functioning code will never purposefully trigger a null pointer exception. Thus, it makes sense to set your debugger to stop every time one happens. In the case of #1, you'll probably get such exceptions routinely.
You should not catch any exceptions that you can't handle, because that will just obfuscate errors that may (or rather, will) bite you later on. Show activity on this post. I would recommend against this practice.
Consider the fact that there are really three (or more) code blocks in play here:
try {} catch (myexcption) {} catch (myotherexception) {} finally {}
Keep in mind that these are in the scope of a larger context and the exceptions not caught are potentually caught further up the stack.
Note that this is basically the same thing as a class construct that also has the {} structure.
Say for instance you might have:
try try if (iAmnotsane) beatMe(please); catch (Exception myexception) catch (myotherexception) logerror("howdy") finally
NOW does that second catch belong to the first or the second try? What about the finally? SO you see the optional/multiple portions make the requirement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With