Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Try-Catch require curly braces

Tags:

c#

try-catch

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.

like image 756
Shlomo Avatar asked Oct 22 '10 17:10

Shlomo


People also ask

Can we skip the curly braces?

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.

Is it bad practice to use try catch?

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.

Why you should avoid try catch?

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.

Should I wrap everything try catch?

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.


1 Answers

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.

like image 194
Mark Schultheiss Avatar answered Sep 17 '22 12:09

Mark Schultheiss