简体   繁体   中英

Try and Except catch all errors, except for sys.exit()

I have created a function, but errors could pop up. That is why I want to use exceptions to generalize all errors into the same message.

However, this function contains multiple sys.exit() calls.

As a result, I would like to have my code jump into the except handler if an error was raised, unless it is caused by sys.exit() . How do I do this?

try:
   myFunction()
except:
   print "Error running myFunction()"

def myFunction():
   sys.exit("Yolo")

You should not use a blanket except , but instead catch Exception :

try:
    myFunction()
except Exception:
   print "Error running myFunction()"

The Exception class is the base class for most exceptions, but not SystemExit . Together with GeneratorExit and KeyboardInterrupt , SystemExit is a subclass of BaseException instead:

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
     +-- Everything else

Exception on the other hand is also a subclass of BaseException , and the rest of the Python exception classes are derived from it rather than BaseException directly. Catching Exception will catch all those derived exceptions, but not the sibling classes.

See the Exception Hierarchy .

As such you should only very rarely use a blanket except: statement. Alway try to limit an except handler to specific exceptions instead, or at most catch Exception .

While there is validity in knowing what exception you are trying to catch, there are blanket options. The following uses the sys library to catch all exceptions and traceback to process the exception message. This first block of code is a bit redundant but demonstrates how that exception can be assigned to a variable and interpreted. Keep in mind that an exception is returned as a tuple with error class, message, & traceback. As follows:

import sys
import traceback

try:
    myfunction()
except Exception as e:
    e = sys.exc_info()
    print('Error Return Type: ', type(e))
    print('Error Class: ', e[0])
    print('Error Message: ', e[1])
    print('Error Traceback: ', traceback.format_tb(e[2]))

Often, you're just looking for the error class and that can be done very succinctly. (Note the blanket except.)

try:
    myFunction() except:
    print('Error: ', sys.exc_info()[0])

Happy error catching!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM