Setting exit code for custom exception in python

I use custom exceptions to distinguish my exceptions from Python's default exceptions.

Is there a way to define a custom exit code when throwing an exception?

class MyException(Exception): pass def do_something_bad(): raise MyException('This is a custom exception') if __name__ == '__main__': try: do_something_bad() except: print('Oops') # Do some exception handling raise 

In this code, the main function performs several functions in the try code. After I catch the exception, I want to raise it again to save the trace stack.

The problem is that the "raise" always exits 1. I want to exit the script using a special exit code (for my custom exception) and exit 1 in any other case.

I looked at this solution, but that’s not what I am looking for: Setting the exit code in Python when an exception occurs

This solution makes me check every script I use, whether the exception is standard or custom.

I want my custom exception to be able to tell the raise function which exit code to use.

+4
source share
1 answer

You can override sys.excepthook to do what you want:

 import sys class ExitCodeException(Exception): "base class for all exceptions which shall set the exit code" def getExitCode(self): "meant to be overridden in subclass" return 3 def handleUncaughtException(exctype, value, trace): oldHook(exctype, value, trace) if isinstance(value, ExitCodeException): sys.exit(value.getExitCode()) sys.excepthook, oldHook = handleUncaughtException, sys.excepthook 

Thus, you can put this code in a special module, which all your code needs to be imported.

+8
source

Source: https://habr.com/ru/post/1483100/


All Articles