Jason Jason - 3 months ago 26
Python Question

Handling DisambiguationError?

I'm using the

wikipedia
library and I want to handle the
DisambiguationError
as an exception. My first try was

try:
wikipedia.page('equipment') # could be any ambiguous term
except DisambiguationError:
pass


During execution line 3 isn't reached. A more general question is: how can I find the error type for a library-specific class like this?

BPL BPL
Answer

Here's a working example:

import wikipedia

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

Regarding to your more general question how can I find the error type for a library-specific class like this?, my trick is actually quite simple, I tend to capture Exception and then just printing the __class__, that way I'll know what specific Exception I need to capture.

One example of figuring out which specific exception to capture here:

try:
    0/0
except Exception as e:
    print("Exception.__class__: {0}".format(e.__class__))

This would print Exception.__class__: <type 'exceptions.ZeroDivisionError'>, so I knew exceptions.ZeroDivisionError would be the exact Exception to deal with instead of something more generic

Comments