How can I write a try
/except
block that catches all exceptions?
Apart from a bare except:
clause (which as others have said you shouldn't use), you can simply catch Exception:
import traceback
import logging
try:
whatever()
except Exception as e:
logging.error(traceback.format_exc())
# Logs the error appropriately.
You would normally only ever consider doing this at the outermost level of your code if for example you wanted to handle any otherwise uncaught exceptions before terminating.
The advantage of except Exception
over the bare except
is that there are a few exceptions that it wont catch, most obviously KeyboardInterrupt
and SystemExit
: if you caught and swallowed those then you could make it hard for anyone to exit your script.
I've just found out this little trick for testing if exception names in Python 2.7 . Sometimes i have handled specific exceptions in the code, so i needed a test to see if that name is within a list of handled exceptions.
try:
raise IndexError #as test error
except Exception as e:
excepName = type(e).__name__ # returns the name of the exception
To catch all possible exceptions, catch BaseException
. It's on top of the Exception hierarchy:
Python 3: https://docs.python.org/3.5/library/exceptions.html#exception-hierarchy
Python 2.7: https://docs.python.org/2.7/library/exceptions.html#exception-hierarchy
try:
something()
except BaseException as error:
print('An exception occurred: {}'.format(error))
But as other people mentioned, you would usually not need this, only for specific cases.
try:
whatever()
except:
# this will catch any exception or error
It is worth mentioning this is not proper Python coding. This will catch also many errors you might not want to catch.
You can do this to handle general exceptions
try:
a = 2/0
except Exception as e:
print e.__doc__
print e.message
Very simple example, similar to the one found here:
http://docs.python.org/tutorial/errors.html#defining-clean-up-actions
If you're attempting to catch ALL exceptions, then put all your code within the "try:" statement, in place of 'print "Performing an action which may throw an exception."'.
try:
print "Performing an action which may throw an exception."
except Exception, error:
print "An exception was thrown!"
print str(error)
else:
print "Everything looks great!"
finally:
print "Finally is called directly after executing the try statement whether an exception is thrown or not."
In the above example, you'd see output in this order:
1) Performing an action which may throw an exception.
2) Finally is called directly after executing the try statement whether an exception is thrown or not.
3) "An exception was thrown!" or "Everything looks great!" depending on whether an exception was thrown.
Hope this helps!