I'd like to know how to handle different exceptions that have the same "type". I'm trying to use some code to make a directory:
os.mkdir(target_dir_name)
And I know this can fail for a variety of reasons, for example if the directory already exists:
OSError: [Errno 17] File exists:
or if there's no permissions to create a new dir:
OSError: [Errno 13] Permission denied:
I'd like to tailor my error messages to the specific failure cause, so I came up with the following code:
try:
os.mkdir(target_dir_name)
except OSError as e:
if e.errno == 17:
print "Warning: Directory %s already exists, executing a rebuild" % (target_dir_name)
elif e.errno == 13:
sys.exit("Error: Directory "+target_dir_name+" cannot be created incorrect permissions")
but I'd like to do something a little less hardcoded. Is there a Pythonic way I could update my sub-failure checks?