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

2

7

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")
Petes answered 5/10, 2014 at 2:56 Comment(1)
Also, you should change your function so that it doesn't call sys.exit. That makes it difficult to use in other ways. For example, it's hard to test.Soleure
T
18

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.

Thaxton answered 5/10, 2014 at 2:57 Comment(1)
To doubly emphasise the last line: you should only extremely rarely catch Exception. You should almost always know the specific type(s) of exception(s) that your code might throw, and catch only those.Rusel
X
5

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!

Xuanxunit answered 8/1, 2019 at 19:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.