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

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

提交回复
热议问题