11

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.

Community
  • 1
  • 1
Nir
  • 894
  • 3
  • 13
  • 24
  • I agree completely. The old Q you pointed at suffers from solving the issue by having to encapsulate your whole program in a `try`/`except` clause. – Alfe May 28 '13 at 08:33

1 Answers1

15

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.

Alfe
  • 56,346
  • 20
  • 107
  • 159
  • Thanks. I preferred wrapping my code in a try block rather than overriding `sys.excepthook`, but it's still a nice solution. – Nir May 22 '14 at 14:11
  • Of course; I was under the impression that this question was about the cases in which no try/except idiom was catching the exception. (Or, as in the question stated itself, if the except-block re-raises the caught exception.) – Alfe May 23 '14 at 08:03
  • 2
    And: wow. an accept of my answer 360 days after the answer was given. That should give me a special badge (long fuse or something) ;-) – Alfe May 23 '14 at 08:07