Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
like image 241
James the Great Avatar asked Dec 02 '22 18:12

James the Great


1 Answers

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.

like image 63
Martijn Pieters Avatar answered Dec 31 '22 14:12

Martijn Pieters