Why does Try-Catch require curly braces

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

    Probably to discourage overuse. A try-catch block is big and ugly, and you're going to notice when you're using it. This mirrors the effect that a catch has on your application's performance - catching an exception is extremely slow compared to a simple boolean test.

    In general you should avoid errors, not handle them. In the example you give, a much more efficient method would be to use

    if(!int.TryParse(s, out i))
     i=0;
    
    0 讨论(0)
  • 2020-12-14 00:37

    The simplest (I think) answer is that each block of code in C/C++/C# requires curly braces.

    EDIT #1

    In response to negative votes, directly from MSDN:

    try-catch (C# Reference)

    The try-catch statement consists of a try block followed by one or more catch clauses, which specify handlers for different exceptions.

    As per definition says, it is a block, so it requires curly braces. That is why we cannot use it without { }.

    0 讨论(0)
  • 2020-12-14 00:38
    try // 1
    try // 2
      something();
    catch { // A
    }
    catch { // B
    }
    catch { // C
    }
    

    does B catches try 1 or 2?

    I don't think you can resolve this unambiguously, since the snippet might mean:

    try // 1
    {
        try // 2
            something();
        catch { // A
        }
    }
    catch { // B
    }
    catch { // C
    }
    
    
    try // 1
    {
        try // 2
            something();
        catch { // A
        }
        catch { // B
        }
    }
    catch { // C
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题