How can I write a `try`/`except` block that catches all exceptions?
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Sunrise at the Stream
--
Chapters
00:00 How Can I Write A `Try`/`Except` Block That Catches All Exceptions?
00:14 Accepted Answer Score 766
00:41 Answer 2 Score 1359
01:17 Answer 3 Score 65
02:04 Answer 4 Score 120
02:13 Thank you
--
Full question
https://stackoverflow.com/questions/4990...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #exception
#avk47
ANSWER 1
Score 1359
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.
ACCEPTED ANSWER
Score 766
You can but you probably shouldn't:
try:
    do_something()
except:
    print("Caught it!")
However, this will also catch exceptions like KeyboardInterrupt and you usually don't want that, do you? Unless you re-raise the exception right away - see the following example from the docs:
try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as (errno, strerror):
    print("I/O error({0}): {1}".format(errno, strerror))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise
ANSWER 3
Score 120
You can do this to handle general exceptions
try:
    a = 2/0
except Exception as e:
    print e.__doc__
    print e.message
ANSWER 4
Score 65
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!