I'm catching exceptions with a try...except block in Python. The program tries to create a directory tree using os.makedirs. If it raises WindowsError: directory already exists, I want to catch the exception and just do nothing. If any other exception is thrown, I catch it and set a custom error variable and then continue with the script. What would theoretically work is the following:
try:
os.makedirs(path)
except WindowsError: print "Folder already exists, moving on."
except Exception as e:
print e
error = 1
Now I want to enhance this a bit and make sure that the except block for WindowsError only treats those exceptions where the error message contains "directory already exists" and nothing else. If there is some other WindowsError I want to treat it in the next except statement. But unfortunately, the following code does not work and the Exception does not get caught:
try:
os.makedirs(path)
except WindowsError as e:
if "directory already exists" in e:
print "Folder already exists, moving on."
else: raise
except Exception as e:
print e
error = 1
How can I achieve that my first except statement specifically catches the "directory already exists" exception and all others get treated in the second except statement?
By handling multiple exceptions, a program can respond to different exceptions without terminating it. In Python, try-except blocks can be used to catch and respond to one or multiple exceptions. In cases where a process raises more than one possible exception, they can all be handled using a single except clause.
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.
The except:pass construct essentially silences any and all exceptional conditions that come up while the code covered in the try: block is being run. What makes this bad practice is that it usually isn't what you really want.
It is possible to have multiple except blocks for one try block. Let us see Python multiple exception handling examples. When the interpreter encounters an exception, it checks the except blocks associated with that try block. These except blocks may declare what kind of exceptions they handle.
Use one exception block and special case your handling there; you can just use isinstance()
to detect a specific exception type:
try:
os.makedirs(path)
except Exception as e:
if isinstance(e, WindowsError) and "directory already exists" in e:
print "Folder already exists, moving on."
else:
print e
error = 1
Note that I'd not rely on the container-like nature of exceptions here; I'd test the args
attribute explicitly:
if isinstance(e, WindowsError) and e.args[0] == "directory already exists":
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