15

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
  • 50,427
  • 120
  • 308
  • 488

2 Answers2

15

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
  • 13,213
  • 8
  • 40
  • 70
  • 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
3

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
  • 44,693
  • 14
  • 86
  • 111
  • 1
    Why do we need to subclass exception? – ampersand Apr 01 '21 at 21:03
  • @ampersand https://docs.python.org/3/library/exceptions.html and https://docs.python.org/3/tutorial/errors.html#tut-userexceptions may help. – hiro protagonist Apr 02 '21 at 05:37
  • 1
    The way you derive from Exception is much shorter than the one in the accepted answer. To me, your version seems absolutely sufficient for distinguishing exceptions when it comes to catching them. Would you agree that writing an own `__init__` here does nothing but increasing noise? – Wolf Dec 19 '22 at 10:11
  • @Wolf that depends a bit on what your goal is. but in this case: i agree! – hiro protagonist Dec 20 '22 at 08:15
  • 1
    Thanks for stopping by. To me, it seems that for the sole purpose of classifying (and hierarchizing) errors, the `pass` implementation will be a good option. Custom constructors are of course needed as soon as there exist additional fields to initialize in the exception class. – Wolf Dec 21 '22 at 09:47