Handle Arbitrary Exception, Print Default Exception Message

前端 未结 5 622
我寻月下人不归
我寻月下人不归 2021-01-01 16:00

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

相关标签:
5条回答
  • 2021-01-01 16:33

    Consider using the Python logging module, this is will give you a lot of the functionality to log problems for later inspection. Below is a simple example of using the logging module to to log exceptions:

    import logging
    LOG_FILE = '/tmp/exceptions.log'
    logging.basicConfig(filename=LOG_FILE,level=logging.ERROR)
    
    while True:
    try:
        # Code that may throw exceptions
    except Exception, e:
        logging.exception("An exception happened")
    

    By using the logging.exception function within an exception handler as is done here the Exception info is automatically added to the logging message.

    0 讨论(0)
  • 2021-01-01 16:37

    I find this to be much more useful for debugging:

    from traceback import print_exc
    try:
        raise Exception("doh!")
    except:
        print_exc()
    
    0 讨论(0)
  • 2021-01-01 16:41
    while True:
        try:
            # Do your stuff
        except Exception, e:
            print "Something happened: %s" % e
    
    0 讨论(0)
  • 2021-01-01 16:42
    try:
        #stuff
    except Exception as e:
        print e
    

    The traceback module provides various functions for extracting more information from the exception object (e, above).

    Source Errors and Exceptions

    0 讨论(0)
  • 2021-01-01 16:55

    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:

    • built-in system-exiting exceptions, like a KeyboardInterrupt from the user hitting ^C (2.5 and later only)
    • user-defined exceptions that don't follow that "should"

    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.

    0 讨论(0)
提交回复
热议问题