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

后端 未结 28 2430
时光说笑
时光说笑 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:06

    Part of the reason they are not in the same scope is because at any point of the try block, you can have thrown the exception. If they were in the same scope, its a disaster in waiting, because depending on where the exception was thrown, it could be even more ambiguous.

    At least when its declared outside of the try block, you know for sure what the variable at minimum could be when an exception is thrown; The value of the variable before the try block.

    0 讨论(0)
  • 2020-11-28 04:07

    Instead of a local variable, a public property could be declared; this also should avoid another potential error of an unassigned variable. public string S { get; set; }

    0 讨论(0)
  • 2020-11-28 04:07

    If the assignment operation fails your catch statement will have a null reference back to the unassigned variable.

    0 讨论(0)
  • 2020-11-28 04:08

    You solution is exactly what you should do. You can't be sure that your declaration was even reached in the try block, which would result in another exception in the catch block.

    It simply must work as separate scopes.

    try
        dim i as integer = 10 / 0 ''// Throw an exception
        dim s as string = "hi"
    catch (e)
        console.writeln(s) ''// Would throw another exception, if this was allowed to compile
    end try
    
    0 讨论(0)
  • 2020-11-28 04:10

    How could you be sure, that you reached the declaration part in your catch block? What if the instantiation throws the exception?

    0 讨论(0)
  • 2020-11-28 04:11

    My thought would be that because something in the try block triggered the exception its namespace contents cannot be trusted - ie referencing the String 's' in the catch block could cause the throw of yet another exception.

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