_conditionally_ returning to point where exception was raised?

Skip Montanaro skip at pobox.com
Wed Mar 16 15:20:58 EST 2005


    >> ... The calling method detects the exception, but needs to get input
    >> from the user before deciding whether A.CalledMethod() should
    >> continue being executed or permantently stop/cancel the execution of
    >> the remaining code in A.CalledMethod(). Can this be done?

    Bengt> Once an exception is raised, the stack gets unwound to the point
    Bengt> where the exception is caught, so there is no way[1] to recover
    Bengt> the context required to "continue" (and eventually "return
    Bengt> normally" as if the exception hadn't happened).

I suspect in the OP's case if A.CalledMethod hasn't gone too far before
encountering an IOError it's quite reasonable to thing that B.CallingMethod
just call A.CalledMethod again if it decides to continue.

I will point out that someone posted some "autoload" code here awhile ago
(who was it?) to try to import missing modules.  I use a variant in my
Python startup file:

    % python
    Python 2.5a0 (#75, Mar 15 2005, 21:55:51) 
    [GCC 3.3 20030304 (Apple Computer, Inc. build 1671)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> print sin(5)
    found sin in math module
    -0.958924274663
    >>> conn = MySQLdb.Connection
    autoloading MySQLdb
    >>> conn
    <function Connect at 0x136abb0>

After finding the module that needs to be imported, it reexecutes the code
object for the frame where the exception was raised:

    exec import_stmt in f_locals, f_globals
    exec tb.tb_frame.f_code in f_locals, f_globals

That's not exactly what the OP asked for (it executes the code object from
the beginning, not from the point where the exception was raised with
possibly modified locals and globals), but might provide people with some
ideas.  The full autoload module is at

    http://manatee.mojam.com/~skip/python/autoload.py

Skip



More information about the Python-list mailing list