Nir*_*Nir 8 python exception raise
我使用自定义异常来区分Python的默认异常.
有没有办法在引发异常时定义自定义退出代码?
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
Run Code Online (Sandbox Code Playgroud)
在此代码中,main函数在try代码中运行一些函数.在我捕获异常后,我想重新提升它以保留回溯堆栈.
问题是'raise'总是退出1.我想用自定义退出代码(对于我的自定义异常)退出脚本,并在任何其他情况下退出1.
我已经看过这个解决方案,但它不是我想要的: 在引发异常时在Python中设置退出代码
这个解决方案迫使我检查我使用的每个脚本,无论异常是默认还是自定义.
我希望我的自定义异常能够告诉raise函数使用哪个退出代码.
Alf*_*lfe 11
您可以覆盖sys.excepthook以执行您自己想要的操作:
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
Run Code Online (Sandbox Code Playgroud)
这样,您可以将此代码放在一个特殊模块中,您需要导入所有代码.
| 归档时间: |
|
| 查看次数: |
4527 次 |
| 最近记录: |