[英]Python compatibility: Catching exceptions
我有一個應用程序,需要在所有“現代”Python版本中工作,這意味着2.5
- 3.2
。 我不想要兩個代碼庫,所以2to3
不是一個選項。
考慮這樣的事情:
def func(input):
if input != 'xyz':
raise MyException(some_function(input))
return some_other_function(input)
如何捕獲此異常,以獲取對異常對象的訪問權限? except MyException, e:
在Python 3中無效, except MyException as e:
在python 2.5中無效。
顯然,它本可以返回異常對象,但我希望,我不必這樣做。
這個問題在Py3k文檔中得到了解決 。 解決方案是檢查sys.exc_info() :
from __future__ import print_function
try:
raise Exception()
except Exception:
import sys
print(sys.exc_info()) # => (<type 'exceptions.Exception'>, Exception(), <traceback object at 0x101c39830>)
exc = sys.exc_info()[1]
print(type(exc)) # => <type 'exceptions.Exception'>
print([a for a in dir(exc) if not a.startswith('__')]) # => ['args', 'message']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.