views:

16

answers:

2

How is the scoping of variables handled during exceptions? I suppose this will be language specific, and answers for any specific language are greatly appreciated. At least maybe the big ones? C++, python, Java. This is what I mean:

python


        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 #?

Or something more complicated, like nested blocks:


    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 #?
A: 

In java, I believe you can not do the following:

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

You must instead do:

String s = null;

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

In other words, the scope of the variable is limited to the block in which it is defined.

HTH

RMorrisey
A: 

A good way to think about this question is to look at it without exceptions. That is, ask yourself variable-scoping in the context of other control entities: if, for, while, do-while, and such. Once you leave the current scope, the program is free to call the GC (or in the case of C++ the destructor) on any left-overs just like it normally would.

wheaties