Why does Try-Catch require curly braces

前端 未结 10 1028
一整个雨季
一整个雨季 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:41

    The first think I can think of is that the curly braces create a block with its own variable scope.

    Look at the following code

    try
    {
        int foo = 2;
    }
    catch (Exception)
    {
        Console.WriteLine(foo); // The name 'foo' does not exist in the current context
    }
    

    foo is not accessible in the catch block due to the variable scoping. I think this makes it easier to reason about whether an variable has been initialized before use or not.

    Compare with this code

    int foo;
    try
    {
        foo = 2;
    }
    catch (Exception)
    {
        Console.WriteLine(foo); // Use of unassigned local variable 'foo'
    }
    

    here you can not guarantee that foo is initialized.

提交回复
热议问题