13

I'm using a python library in which at one point an exception is defined as follows:

raise Exception("Key empty")

I now want to be able to catch that specific exception, but I'm not sure how to do that.

I tried the following

try:
    raise Exception('Key empty')
except Exception('Key empty'):
    print 'caught the specific exception'
except Exception:
    print 'caught the general exception'

but that just prints out caught the general exception.

Does anybody know how I can catch that specific Key empty exception? All tips are welcome!

kramer65
  • 45,059
  • 106
  • 285
  • 459

2 Answers2

10

Define your exception:

class KeyEmptyException(Exception):
    def __init__(self, message='Key Empty'):
        # Call the base class constructor with the parameters it needs
        super(KeyEmptyException, self).__init__(message)

Use it:

try:
    raise KeyEmptyException()
except KeyEmptyException as e:
    print e

Update: based on the discussion in comment OP posted:

But the lib is not under my control. It's open source, so I can edit it, but I would preferably try to catch it without editing the library. Is that not possible?

say library raises an exception as

# this try is just for demonstration 
try:

    try:
        # call your library code that can raise `Key empty` Exception
        raise Exception('Key empty')
    except Exception as e:
        # if exception occurs, we will check if its 
        # `Key empty` and raise our own exception
        if str(e) == 'Key empty':
            raise KeyEmptyException()
        else:
            # else raise the same exception
            raise e
except Exception as e:
    # we will finally check what exception we are getting
    print('Caught Exception', e)
Vikash Singh
  • 11,953
  • 7
  • 36
  • 67
  • 1
    But the lib is not under my control. It's open source, so I can edit it, but I would preferably try to catch it without editing the library. Is that not possible? – kramer65 Aug 17 '17 at 12:38
  • I would even choose RuntimeError as the base class. – Gribouillis Aug 17 '17 at 12:38
  • if the exception that is raised by the library is fixed. Then you have to catch that exception. You can catch that exception and raise your own exception in return. – Vikash Singh Aug 17 '17 at 12:40
2

you need to subclass Exception:

class EmptyKeyError(Exception):
    pass

try:
    raise EmptyKeyError('Key empty')
except EmptyKeyError as exc:
    print(exc)
except Exception:
    print('caught the general exception')
hiro protagonist
  • 40,708
  • 13
  • 78
  • 98