Why aren't variables declared in “try” in scope in “catch” or “finally”?

后端 未结 28 2559
时光说笑
时光说笑 2020-11-28 03:44

In C# and in Java (and possibly other languages as well), variables declared in a \"try\" block are not in scope in the corresponding \"catch\" or \"finally\" blocks. For e

28条回答
  •  攒了一身酷
    2020-11-28 04:18

    Traditionally, in C-style languages, what happens inside the curly braces stays inside the curly braces. I think that having the lifetime of a variable stretch across scopes like that would be unintuitive to most programmers. You can achieve what you want by enclosing the try/catch/finally blocks inside another level of braces. e.g.

    ... code ...
    {
        string s = "test";
        try
        {
            // more code
        }
        catch(...)
        {
            Console.Out.WriteLine(s);
        }
    }
    

    EDIT: I guess every rule does have an exception. The following is valid C++:

    int f() { return 0; }
    
    void main() 
    {
        int y = 0;
    
        if (int x = f())
        {
            cout << x;
        }
        else
        {
            cout << x;
        }
    }
    

    The scope of x is the conditional, the then clause and the else clause.

提交回复
热议问题