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

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

    Well if it doesn't throw a compile error, and you could declare it for the rest of the method, then there would be no way to only declare it only within try scope. It's forcing you to be explicit as to where the variable is supposed to exists and doesn't make assumptions.

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

    When you have a try catch, you should at the most part know that errors that it might throw. Theese Exception classes normaly tell everything you need about the exception. If not, you should make you're own exception classes and pass that information along. That way, you will never need to get the variables from inside the try block, because the Exception is self explainatory. So if you need to do this alot, think about you're design, and try to think if there is some other way, that you can either predict exceptions comming, or use the information comming from the exceptions, and then maybe rethrow your own exception with more information.

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

    The C# Spec (15.2) states "The scope of a local variable or constant declared in a block ist the block."

    (in your first example the try block is the block where "s" is declared)

    0 讨论(0)
  • 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.

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