How can I write a `try`/`except` block that catches all exceptions? How can I write a `try`/`except` block that catches all exceptions? python python

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 tracebackimport loggingtry:    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.


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


To catch all possible exceptions, catch BaseException. It's on top of the Exception hierarchy:

Python 3:https://docs.python.org/3.9/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.


matomo