python自定义异常代码_在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.

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值