Why does Try-Catch require curly braces

前端 未结 10 1112
一整个雨季
一整个雨季 2020-12-13 23:57

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 = DateT         


        
10条回答
  •  一整个雨季
    2020-12-14 00:35

    If you assume that the designers of C# simply choose to use the same syntax as C++ then the question becomes why are braces necessary with single statements try and catch blocks in C++. The simple answer is that Bjarne Stroustrup thought the syntax was easier to explain.

    In The Design and Evolution of C++ Stroustrup writes:

    "The try keyword is completely redundant and so are the { } braces except where multiple statements are actually used in a try-block or a handler."

    He goes on to give an example where the try keyword and { } are not needed. He then writes:

    "However, I found this so difficult to explain that the redundancy was introduced to save support staff from confused users."

    Reference: Stroustrup, Bjarne (1994). The Design and Evolution of C++. Addison-Wesley.

提交回复
热议问题