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

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

    try: someFunction() except Exception, exc:

    #this is how you get the type
    excType = exc.__class__.__name__
    
    #here we are printing out information about the Exception
    print 'exception type', excType
    print 'exception msg', str(exc)
    
    #It's easy to reraise an exception with more information added to it
    msg = 'there was a problem with someFunction'
    raise Exception(msg + 'because of %s: %s' % (excType, exc))
    

提交回复
热议问题