[Python-ideas] with statement vs. try...except...finally

Steven D'Aprano steve at pearwood.info
Sat May 30 02:30:40 CEST 2009


On Sat, 30 May 2009 06:58:55 am Gerald Britton wrote:

> I guess I'm wondering if we need a with...except construct so that we
> can get exceptions that happen after the with context is entered
> without wrapping the with statement in try...except.

Would this hypothetical construct:

with some_context_manager() as obj:
    do_something_with(obj)
except Exception:
    error_handler()


catch exceptions in the context manager, the do_something_with() block, 
or both? Give reasons for why you make that choice.


Personally, I don't see the need for this. We can already do:

# Catch errors in both the context manager and the with block
try:
    with open(filename) as f:
        process(f)
except Exception:
    pass


or this:

# Catch errors in just the with block
with open(filename) as f:
    try:
        process(f)
    except Exception:
        pass

or this:

# Catch errors in the context manager and the with block separately:
try:
    with open(filename) as f:
        try:
            process(f)
        except Exception:
            print "Error in the with block"
except Exception:
     print "Error in the context manager"


and if for some bizarre reason you want to catch errors in the context 
manager but not the body of with, you can manually emulate with:

# untested
try:
    try:
        f = open(filename).__enter__()
    except Exception:
        f = None
    process(f)
finally:
    if f is not None:
        f.__exit__()


That fourth case is ugly, but it's also rare. I can't imagine a case 
where you'd need it, but if you do, you can do it.

The point is, you can make your error handlers as fine grained as you 
want, by wrapping just the bits you need. You can nest try blocks, or 
execute them sequentially. All the flexibility you want is there, at 
the cost of nothing but an extra line and an indent level. What does 
with...except gain you that you can't already do easily?



-- 
Steven D'Aprano



More information about the Python-ideas mailing list