3

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?

Jason
  • 884
  • 8
  • 28

1 Answers1

5

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

BPL
  • 9,632
  • 9
  • 59
  • 117
  • 1
    @Jason Yeah, you're right, I've edited my code to become more clear for other people ;-) – BPL Sep 01 '16 at 20:37
  • Ha, I just realized I didn't read carefully enough and your code was pretty clear in the first place. I guess extra clarity can't hurt though! – Jason Sep 01 '16 at 20:37