Catch any error in Python

前端 未结 8 1656
一个人的身影
一个人的身影 2021-02-01 14:24

Is it possible to catch any error in Python? I don\'t care what the specific exceptions will be, because all of them will have the same fallback.

相关标签:
8条回答
  • 2021-02-01 14:59

    Quoting the bounty text:

    I want to be able to capture ANY exception even weird ones like keyboard interrupt or even system exit (e.g. if my HPC manger throws an error) and get a handle to the exception object e, whatever it might be. I want to process e and custom print it or even send it by email

    Look at the exception hierarchy, you need to catch BaseException:

    BaseException
     +-- SystemExit
     +-- KeyboardInterrupt
     +-- GeneratorExit
     +-- Exception
    

    This will capture KeyboardInterrupt, SystemExit, and GeneratorExit, which all inherit from BaseException but not from Exception, e.g.

    try:
        raise SystemExit
    except BaseException as e:
        print(e.with_traceback)
    
    0 讨论(0)
  • 2021-02-01 15:01

    Using except by itself will catch any exception short of a segfault.

    try:
        something()
    except:
        fallback()
    

    You might want to handle KeyboardInterrupt separately in case you need to use it to exit your script:

    try:
        something()
    except KeyboardInterrupt:
        return
    except:
        fallback()
    

    There's a nice list of basic exceptions you can catch here. I also quite like the traceback module for retrieving a call stack from the exception. Try traceback.format_exc() or traceback.print_exc() in an exception handler.

    0 讨论(0)
  • 2021-02-01 15:08

    You might want also to look at sys.excepthook:

    When an exception is raised and uncaught, the interpreter calls sys.excepthook with three arguments, the exception class, exception instance, and a traceback object. In an interactive session this happens just before control is returned to the prompt; in a Python program this happens just before the program exits. The handling of such top-level exceptions can be customized by assigning another three-argument function to sys.excepthook.

    Example:

    def except_hook(type, value, tback):
        # manage unhandled exception here
        sys.__excepthook__(type, value, tback) # then call the default handler
    
    sys.excepthook = except_hook
    
    0 讨论(0)
  • 2021-02-01 15:08

    The following only worked for me (both in PY2 and PY3):

    try:
      # (Anything that produces any kind of error)
    except:
      ertype = sys.exc_info()[0]  # E.g. <class 'PermissionError'>
      description = sys.exc_info()[1]   # E.g. [Errno 13] Permission denied: ...
      # (Handle as needed ) 
    
    0 讨论(0)
  • 2021-02-01 15:13

    Not mentioning the type of exception you want to handle itself does the job.

    try this:

        try:
           #code in which you expect an exception 
        except:
           #prints the exception occured
    

    if you want to know the type of exception occurred:

        try:
           #code in which you expect an exception 
        except Exception as e:
           print(e)
           #for any exception to be catched
    

    for detailed explanation go trough this https://www.tutorialspoint.com/python/python_exceptions.htm

    0 讨论(0)
  • 2021-02-01 15:18
    # in python 3
    
    # if you want the error
    try:
        func()
    except Exception as e:
        exceptionFunc(e)
    
    # if you simply want to know an error occurs
    try:
        func()
    except:
        exceptionFunc()
    
    # if you don't even wanna do anything
    try:
        func()
    except:
        pass
    
    0 讨论(0)
提交回复
热议问题