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

后端 未结 15 2063
情书的邮戳
情书的邮戳 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 15:21

    Most answers point to except (…) as (…): syntax (rightly so) but at the same time nobody wants to talk about an elephant in the room, where the elephant is sys.exc_info() function. From the documentation of sys module (emphasis mine):

    This function returns a tuple of three values that give information about the exception that is currently being handled.
    (…)
    If no exception is being handled anywhere on the stack, a tuple containing three None values is returned. Otherwise, the values returned are (type, value, traceback). Their meaning is: type gets the type of the exception being handled (a subclass of BaseException); value gets the exception instance (an instance of the exception type); traceback gets a traceback object (see the Reference Manual) which encapsulates the call stack at the point where the exception originally occurred.

    I think the sys.exc_info() could be treated as the most direct answer to the original question of How do I know what type of exception occurred?

提交回复
热议问题