To my shame, I can't figure out how to handle exception for python 'with' statement. If I have a code:
with open("a.txt") as f: print f.readlines()
I really want to handle 'file not found exception' in order to do somehing. But I can't write
with open("a.txt") as f: print f.readlines() except: print 'oops'
and can't write
with open("a.txt") as f: print f.readlines() else: print 'oops'
enclosing 'with' in a try/except statement doesn't work else: exception is not raised. What can I do in order to process failure inside 'with' statement in a Pythonic way?
Catching Exceptions in Python In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.
Try and Except statement is used to handle these errors within our code in Python.
The try and except block in Python is used to catch and handle exceptions. Python executes code following the try statement as a “normal” part of the program. The code that follows the except statement is the program's response to any exceptions in the preceding try clause.
should I use the throw outside or inside an "if" statement? You definitely should throw exception inside the if condition check.
from __future__ import with_statement try: with open( "a.txt" ) as f : print f.readlines() except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available print 'oops'
If you want different handling for errors from the open call vs the working code you could do:
try: f = open('foo.txt') except IOError: print('error') else: with f: print f.readlines()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With