如何在例外中处理范围

时间:2010-09-13 17:30:05

标签: exception exception-handling scope

在异常期间如何处理变量的范围?我想这将是语言特定的,并且非常感谢任何特定语言的答案。至少可能是大的? C++, python, Java。这就是我的意思:


        try:
            for k, v in map.iteritems():
                cnf.conf.set( section, k, v )
            for i, j in map2.iteritems():
                dosomethingelse()
                for m in range(10):
                    morestuff()
        except SpecificError:
            vars = (k, v, i, j, m)
        finally:
            vars in scope #?

或者更复杂的东西,比如嵌套块:


    try:
        try:
            for k, v in map.iteritems():
                cnf.conf.set( section, k, v )
            for i, j in map2.iteritems():
                dosomethingelse()
                for m in range(10):
                    morestuff()
        except SpecificError:
            vars = (k, v, i, j, m)
    except:
        vars in scope #?

1 个答案:

答案 0 :(得分:1)

在java中,我相信你可以执行以下操作:

try {
 String s = "Hello, finally!";
 ...
}
finally {
 System.out.println(s);
}

你必须改为:

String s = null;

try {
 s = "Hello, finally!";
 ...
}
finally {
 System.out.println(s);
}

换句话说,变量的范围仅限于定义它的块。

HTH