Pass Exception to next except statement - python

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?

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":

Related

Given error when trying to iterate through an exception

I am making a Reddit bot using PRAW and the code gives me the error that the exception is not iterable. Here is a simplification of my code:
try:
#something with praw that isn't relevant
except Exception as e: #this except error catches the APIexception, APIexpections in PRAW are a wide field of exceptions that dont't always have the same solution, so I scan the text for the error I'm looking for.
print(e)
if "keyword thats in the error" in e:
#fix the problem with the specific error
else:
print("Unkown APIExpection error")
This works fine for me, but when I run this code:
try:
#something
except Exception as e:
for character in e:
print(character)
#I also tried this
try:
#something
except Exception as e:
for character in str(e):
print(character)
#None of the above work but this is my actual code and what I need to do, anything that gets the above to work should work here too, I'm just letting you know this so that I don't get any other errors I have to ask another question for.
try:
#something
except Exception as e:
characterNum = 0
for character in e:
characterNum += 1
print(str(characterNum) + ": " + character)
It gives me a "TypeError: 'RedditAPIException' is not iterable", RedditAPIException can be ignore though as that's just the error I'm catching.
Convert the exception to string and then check in the if statement.
Change to => if "keyword thats in the error" in str(e):

Pythonic exception handling: only catching specific errno

I often read that in python "it is easier to ask for forgiveness then for permission", so it is sometimes considered better to use try except instead of if.
I often have statements like
if (not os.path.isdir(dir)):
os.mkdir(dir).
The likely replacement would be
try:
os.mkdir(dir)
except OSError:
pass.
However I would like to be more specific and only ignore the errno.EEXIST, as this is the only error that is expected to happen and I have no idea what could happen.
try:
os.mkdir(dir)
except OSError:
if(OSError.errno != errno.EEXIST):
raise
else:
pass.
Seems to do the trick. But this is really bulky and will 'pollute' my code and reduce readability if I need plenty of these code-blocks. Is there a pythonic way to do this in Python 2.X? What is the standard procedure to handle such cases?
edits:
use raise instead raise OSerror as pointed out by #Francisco Couzo
I use Python 2.7
I just stumbled across the probably most elegant solution: creating the ignored context manager:
import errno
from contextlib import contextmanager
#contextmanager
def ignorednr(exception, *errornrs):
try:
yield
except exception as e:
if e.errno not in errornrs:
raise
pass
with ignorednr(OSError, errno.EEXIST):
os.mkdir(dir)
This way I just have the ugly job of creating the context manager once, from then on the syntax is quite nice and readable.
The solution is taken from https://www.youtube.com/watch?v=OSGv2VnC0go.
If you are calling it multiple times with different args, put it in a function:
def catch(d, err):
try:
os.mkdir(d)
except OSError as e:
if e.errno != err:
raise
Then call the function passing in whatever args:
catch(, "foo", errno.EEXIST)
You could also allow the option of passing passing multiple errno's if you wanted more:
def catch(d, *errs):
try:
os.mkdir(d)
except OSError as e:
if e.errno not in errs:
raise
catch("foo", errno.EEXIST, errno.EPERM)
This example is for exception OSError : 17, 'File exists'
import sys
try:
value = os.mkdir("dir")
except:
e = sys.exc_info()[:2]
e = str(e)
if "17" in e:
raise OSError #Perform Action
else:
pass
Just change the number 17 to your exception number. You can get a better explanation at this link.

Python 2.7 exception handling syntax

I am bit confused about the try exception usage in Python 2.7.
try:
raise valueError("sample value error")
except Exception as e:
print str(e)
try:
raise valueError("sample value error")
except Exception,exception:
print str(exception)
try:
raise valueError("sample value error")
except exception:
print str(exception)
try:
raise valueError("sample value error")
except Exception:
print str(Exception) # it prints only the object reference
can some help me to understand the above usage?
Some concepts to help you understand the difference between the alternate variants of the except variants:
except Exception, e – This in an older variant, now deprecated, similar to except Exception as e
except Exception as e – Catch exceptions of the type Exception (or any subclass) and store them in the variable e for further processing, messaging or similar
except Exception – Catch exceptions of the type Exception (or any subclass), but ignore the value/information provided in the exception
except e – Gives me an compilation error, not sure if this related to python version, but if so, it should/would mean that you don't care about the type of exception but want to access the information in it
except – Catch any exception, and ignore the exception information
What to use, depends on many factors, but if you don't need the provided information in the exception there is no need to present the variable to catch this information.
Regarding which type of Exception to catch, take care to catch the accurate type of exceptions. If you are writing a general catch it all, it could be correct to use except Exception, but in the example case you've given I would opt for actually using except ValueError directly. This would allow for potentially other exceptions to be properly handled at another level of your code. The point is, don't catch exception you are not ready to handle.
If you want, you can read more on python 2.7 exception handling or available python 2.7 exception in the official documentation.
For Python 3 (also works in Python 2.7):
try:
raise ValueError("sample value error")
except Exception as e:
print(e)
For Python 2 (will not work in Python 3):
try:
raise ValueError("sample value error")
except Exception, e:
print e
I use:
try:
raise valueError("sample value error")
except Exception as e:
print str(e)
When I want to declare a specific error and
try:
raise valueError("sample value error")
except:
print "Something unexpected happened"
When I don't really care or except: pass , except: return etc
Use the format
try:
raise ValueError("sample value error")
except Exception, e:
print e

Traced Exceptions? [duplicate]

How can I get the full stack trace from the Exception object itself?
Consider the following code as reduced example of the problem:
last_exception = None
try:
raise Exception('foo failed')
except Exception as e:
last_exception = e
# this happens somewhere else, decoupled from the original raise
print_exception_stack_trace(last_exception)
Edit: I lied, sorry. e.__traceback__ is what you want.
try:
raise ValueError
except ValueError as e:
print( e.__traceback__ )
>c:/python31/pythonw -u "test.py"
<traceback object at 0x00C964B8>
>Exit code: 0
This is only valid in Python 3; you can't do it in earlier versions.

Exception in python unknown errors

except ValueError:
print "the input is Invaild(dd.mm.year)"
except as e:
print "Unknown error"
print e
This is the code I wrote, if an error different then valueerror will happen will it print it in e?
thanks
You'll need to catch the BaseException or object here to be able to assign to e:
except ValueError:
print "the input is Invaild(dd.mm.year)"
except BaseException as e:
print "Unknown error"
print e
or, better still, Exception:
except ValueError:
print "the input is Invaild(dd.mm.year)"
except Exception as e:
print "Unknown error"
print e
The blanket except: will catch the same exceptions as BaseException, catching just Exception will ignore KeyboardInterrupt, SystemExit, and GeneratorExit. Not catching these there is generally a good idea.
For details, see the exceptions documentation.
No, that code will throw a SyntaxError:
If you don't know the exception your code might throw, you can capture for just Exception. Doing so will get all built-in, non-system-exiting exceptions:
except ValueError:
print "the input is Invaild(dd.mm.year)"
except Exception as e:
print "Unknown error"
print e

Categories