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

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

    As has been pointed out by other users, the curly braces define scope in pretty much every C style language that I know of.

    If it's a simple variable, then why do you care how long it will be in scope? It's not that big a deal.

    in C#, if it is a complex variable, you will want to implement IDisposable. You can then either use try/catch/finally and call obj.Dispose() in the finally block. Or you can use the using keyword, which will automatically call the Dispose at the end of the code section.

提交回复
热议问题