The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 4,259 other subscribers

c# – Why does Try-Catch require curly braces – Stack Overflow

Posted by jpluimers on 2017/12/27

From my SO Question Archive:

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.

[WayBackc# – Why does Try-Catch require curly braces – Stack Overflow.

I asked this question partially because of my Delphi background where there are two try statements (one for finally and one for except a.k.a. catch) neither having the braces problem as try/finally/except all are block boundaries.

The most interesting bit was the [WayBackanswer by [WayBack] Eric Lippert (ex C# compiler team, now at Facebook after an intermediate position at Coverty) referring to his [WayBackWhy are braces required in try-catch-finally? | Fabulous adventures in coding  blog entry.

The answer and blog entry come down to preventing ambiguity.

His answer reveals that a compound try/catch/finally statement is converted by two try statements like this:

try
{
  try
  {
      XYZ();
  }
  catch(whatever)
  {
     DEF();
  }
}
finally
{
  ABC();
}

This emphasises that catch and finally are conceptually indeed two different things which statistics show.

I need to dig up the numbers (I remember researching this for Java and Delphi code a very long time ago – think Delphi 7 era – and C# code a long time ago – think C# 2 era), but this comment should still hold:

My observation in most code I’ve seen is that the combination of catch and finally is hardly (i.e. far less than 1%) used in the same statement (or in other languages in nested statements), because they serve two very different purposes. That’s why I prefer not to mix them, and if I do, use the nested construction to both emphasize the difference in purpose, and execution order. Learning new things every day: How often is your occasionally percentage wise? – Jeroen Wiert Pluimers Dec 23 ’12 at 19:34

–jeroen

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.