Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting an exit code for a custom exception in python

I'm using custom exceptions to differ my exceptions from Python's default exceptions.

Is there a way to define a custom exit code when I raise the 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 runs a few functions in a try code. After I catch an exception I want to re-raise it to preserve the traceback stack.

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

I've looked at this solution but it's not what I'm looking for: Setting exit code in Python when an exception is raised

This solution forces me to check in every script I use whether the exception is a default or a custom one.

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

like image 987
Nir Avatar asked May 28 '13 07:05

Nir


People also ask

How do you set an exit code in Python?

A process can also set its exit code when explicitly exiting. This can be achieved by calling the sys. exit() function and passing the exit code as an argument. The sys.

How do I return a custom exception in Python?

In Python, users can define custom exceptions by creating a new class. This exception class has to be derived, either directly or indirectly, from the built-in Exception class. Most of the built-in exceptions are also derived from this class.

Does Python exit after exception?

It inherits from BaseException instead of Exception so that it is not accidentally caught by code that catches Exception . This allows the exception to properly propagate up and cause the interpreter to exit. When it is not handled, the Python interpreter exits; no stack traceback is printed.


1 Answers

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

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

This way you can put this code in a special module which all your code just needs to import.

like image 120
Alfe Avatar answered Sep 24 '22 01:09

Alfe