python: How do I know what type of exception occurred?

后端 未结 15 1912
情书的邮戳
情书的邮戳 2020-11-29 14:56

I have a function called by the main program:

try:
    someFunction()
except:
    print \"exception happened!\"

but in the middle of the ex

相关标签:
15条回答
  • 2020-11-29 14:57

    These answers are fine for debugging, but for programmatically testing the exception, isinstance(e, SomeException) can be handy, as it tests for subclasses of SomeException too, so you can create functionality that applies to hierarchies of exceptions.

    0 讨论(0)
  • 2020-11-29 15:04

    To add to Lauritz's answer, I created a decorator/wrapper for exception handling and the wrapper logs which type of exception occurred.

    class general_function_handler(object):
        def __init__(self, func):
            self.func = func
        def __get__(self, obj, type=None):
            return self.__class__(self.func.__get__(obj, type))
        def __call__(self, *args, **kwargs):
            try:
                retval = self.func(*args, **kwargs)
            except Exception, e :
                logging.warning('Exception in %s' % self.func)
                template = "An exception of type {0} occured. Arguments:\n{1!r}"
                message = template.format(type(e).__name__, e.args)
                logging.exception(message)
                sys.exit(1) # exit on all exceptions for now
            return retval
    

    This can be called on a class method or a standalone function with the decorator:

    @general_function_handler

    See my blog about for the full example: http://ryaneirwin.wordpress.com/2014/05/31/python-decorators-and-exception-handling/

    0 讨论(0)
  • 2020-11-29 15:07

    Unless somefunction is a very bad coded legacy function, you shouldn't need what you're asking.

    Use multiple except clause to handle in different ways different exceptions:

    try:
        someFunction()
    except ValueError:
        # do something
    except ZeroDivision:
        # do something else
    

    The main point is that you shouldn't catch generic exception, but only the ones that you need to. I'm sure that you don't want to shadow unexpected errors or bugs.

    0 讨论(0)
  • 2020-11-29 15:11

    Hope this will help a little more

    import sys
    varExcepHandling, varExcepHandlingZer = 2, 0
    try:
      print(varExcepHandling/varExcepHandlingZer)
    except Exception as ex: 
      print(sys.exc_info())
    

    'sys.exc_info()' will return a tuple, if you only want the exception class name use 'sys.exc_info()[0]'

    Note:- if you want to see all the exception classes just write dir(__builtin__)

    0 讨论(0)
  • 2020-11-29 15:12

    You can start as Lauritz recommended, with:

    except Exception as ex:
    

    and then just to print ex like so:

    try:
        #your try code here
    except Exception as ex:
        print ex
    
    0 讨论(0)
  • 2020-11-29 15:12

    Your question is: "How can I see exactly what happened in the someFunction() that caused the exception to happen?"

    It seems to me that you are not asking about how to handle unforeseen exceptions in production code (as many answers assumed), but how to find out what is causing a particular exception during development.

    The easiest way is to use a debugger that can stop where the uncaught exception occurs, preferably not exiting, so that you can inspect the variables. For example, PyDev in the Eclipse open source IDE can do that. To enable that in Eclipse, open the Debug perspective, select Manage Python Exception Breakpoints in the Run menu, and check Suspend on uncaught exceptions.

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