I have a program, a part of which executes a loop. During the execution of this loop, there are exceptions. Obviously, I would like my program to run without errors, but for
While James's answer is almost always what you actually want, it's not quite what the OP asked for:
Is there a way to except any arbitrary exception and be able to print out the exception message in the except block?
Exception doesn't actually handle all exceptions, just all exceptions you usually want to catch. In particular, in 2.5 and later:
All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from this class.
This leaves out a few things:
^C (2.5 and later only)Very occasionally, you want to handle things like KeyboardInterrupt, in which case you use BaseException instead of Exception. (See Exception hierarchy for a list of which exceptions are and are not Exception subclasses.) So:
try:
# stuff
except BaseException as e:
print e
And (usually temporarily while debugging) sometimes you really do want to handle absolutely everything. In 2.7, that includes exceptions defined as old-style classes; in 2.5 and earlier, it also includes strings. The only way to handle all of those possibilities is to use a bare except and then use sys.exc_info (and, optionally, re-raise anything you didn't want to handle):
try:
# stuff
except:
type, value, traceback = sys.exc_info()
print value
As a side note, I'm using the new-style except syntax (except Exception as e) above. This works in 2.6 and later, including 3.x. The old-style syntax (except Exception, e) is deprecated in 2.6, and stops working in 3.0, but if you want to work with older 2.x versions you need to use it.