处理消歧错误?

Jas*_*son 3 python error-handling try-except pywikibot

我正在使用该wikipedia库,并且想将其DisambiguationError作为异常处理。我的第一次尝试是

try:
     wikipedia.page('equipment') # could be any ambiguous term
except DisambiguationError:
     pass
Run Code Online (Sandbox Code Playgroud)

在执行期间,未到达第 3 行。一个更普遍的问题是:如何找到这样的特定于库的类的错误类型?

BPL*_*BPL 5

这是一个工作示例:

import wikipedia

try:
    wikipedia.page('equipment')
except wikipedia.exceptions.DisambiguationError as e:
    print("Error: {0}".format(e))
Run Code Online (Sandbox Code Playgroud)

关于你更一般的问题how can I find the error type for a library-specific class like this?,我的技巧实际上很简单,我倾向于捕获 Exception 然后只打印__class__,这样我就会知道我需要捕获什么特定的 Exception 。

找出在此处捕获哪个特定异常的一个示例:

try:
    0/0
except Exception as e:
    print("Exception.__class__: {0}".format(e.__class__))
Run Code Online (Sandbox Code Playgroud)

这会打印Exception.__class__: <type 'exceptions.ZeroDivisionError'>,所以我知道exceptions.ZeroDivisionError这将是要处理的确切异常,而不是更通用的东西