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

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

    The answer, as everyone has pointed out, is pretty much "that's how blocks are defined".

    There are some proposals to make the code prettier. See ARM

     try (FileReader in = makeReader(), FileWriter out = makeWriter()) {
           // code using in and out
     } catch(IOException e) {
           // ...
     }
    

    Closures are supposed to address this as well.

    with(FileReader in : makeReader()) with(FileWriter out : makeWriter()) {
        // code using in and out
    }
    

    UPDATE: ARM is implemented in Java 7. http://download.java.net/jdk7/docs/technotes/guides/language/try-with-resources.html

提交回复
热议问题