HiveBrain v1.2.0
Get Started
← Back to all entries
debugpythonCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
allhowwriteexceptcatchestryblockcanthatexceptions

Problem

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

Solution

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

Code Snippets

try:
    do_something()
except:
    print("Caught it!")
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

Context

Stack Overflow Q#4990718, score: 784

Revisions (0)

No revisions yet.