本文介绍了当我提出自己的异常时,我如何更容易地抑制以前的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 考虑 try: import someProprietaryModule 除了ImportError: raise ImportError '看来,< someProprietaryModule>未安装...') 运行时,如果someProprietaryModule没有安装,可以看到: (追溯数据) ImportError:未知模块:someProprietaryModule 在处理上述异常时,发生另一个异常: (追溯数据) ImportError:看来< someProprietaryModule>没有安装... 也许我不想要在处理上述异常时。 ..行(及其上方的行)出现。我可以这样做: _moduleInstalled = True try: import someProprietaryModule 除了ImportError : _moduleInstalled = False 如果不是_moduleInstalled: raise ImportError('看来,< someProprietaryModule>未安装...) 但感觉就像是一个黑客。还有什么可以做的?解决方案在Python 3.3和更高版本 raise ... from None try: import someProprietaryModule : raise ImportError('似乎< someProprietaryModule>未安装...)从$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b 这样做有所期望的结果。 Considertry: import someProprietaryModuleexcept ImportError: raise ImportError('It appears that <someProprietaryModule> is not installed...')When run, if someProprietaryModule is not installed, one sees:(traceback data)ImportError: unknown module: someProprietaryModuleDuring handling of the above exception, another exception occurred:(traceback data)ImportError: It appears that <someProprietaryModule> is not installed...Perhaps I don't want the "During handling of the above exception..." line (and the lines above it) to appear. I could do this:_moduleInstalled = Truetry: import someProprietaryModuleexcept ImportError: _moduleInstalled = Falseif not _moduleInstalled: raise ImportError('It appears that <someProprietaryModule> is not installed...')But that feels like a bit of a hack. What else might I do? 解决方案 In Python 3.3 and later raise ... from None may be used in this situation.try: import someProprietaryModuleexcept ImportError: raise ImportError('It appears that <someProprietaryModule> is not installed...') from NoneThis has the desired results. 这篇关于当我提出自己的异常时,我如何更容易地抑制以前的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 07-04 23:01