As a beginner how do I understand event/error handling in python?
The Ultimate Guide to Error Handling in Python
What is a good way to handle exceptions when trying to read a file in Python? - Stack Overflow
exception - Catch any error in Python - Stack Overflow
Error handling is pretty confusing to me and quite difficult for me to understand.
Use this:
try:
f = open(fname, 'rb')
except OSError:
print "Could not open/read file: ", fname
sys.exit()
with f:
reader = csv.reader(f)
for row in reader:
pass # Do stuff here
Here is a read/write example. The with statement ensures the close() statement will be called by the file object regardless of whether an exception is thrown. http://effbot.org/zone/python-with-statement.htm
import sys
fIn = 'symbolsIn.csv'
fOut = 'symbolsOut.csv'
try:
with open(fIn, 'r') as f:
file_content = f.read()
print "read file " + fIn
if not file_content:
print "no data in file " + fIn
file_content = "name,phone,address\n"
with open(fOut, 'w') as dest:
dest.write(file_content)
print "wrote file " + fOut
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except: #handle other exceptions such as attribute errors
print "Unexpected error:", sys.exc_info()[0]
print "done"
Using except by itself will catch any exception short of a segfault.
try:
something()
except:
fallback()
You might want to handle KeyboardInterrupt separately in case you need to use it to exit your script:
try:
something()
except KeyboardInterrupt:
return
except:
fallback()
There's a nice list of basic exceptions you can catch here. I also quite like the traceback module for retrieving a call stack from the exception. Try traceback.format_exc() or traceback.print_exc() in an exception handler.
try:
# do something
except Exception, e:
# handle it
For Python 3.x:
try:
# do something
except Exception as e:
# handle it
This solution will keep the with-block-code outside of the try-except-clause.
try:
f = open('foo.txt')
except FileNotFoundError:
print('error')
else:
with f:
print f.readlines()
The best "Pythonic" way to do this, exploiting the with statement, is listed as Example #6 in PEP 343, which gives the background of the statement.
from contextlib import contextmanager
@contextmanager
def opened_w_error(filename, mode="r"):
try:
f = open(filename, mode)
except IOError, err:
yield None, err
else:
try:
yield f, None
finally:
f.close()
Used as follows:
with opened_w_error("/etc/passwd", "a") as (f, err):
if err:
print "IOError:", err
else:
f.write("guido::0:0::/:/bin/sh\n")