1

Can Python assert be used to check for specific exceptions in a function? For instance, if I have a function that I know will raise a KeyError, can assert detect it? For example:

def get_value(x):
    lookup = {'one': 1}
    return lookup[x]

assert get_value('two') == KeyError

When I run this I just get the KeyError exception. Can assert check something like this? Or is that not what assert is used for?

martineau
  • 119,623
  • 25
  • 170
  • 301
b10hazard
  • 7,399
  • 11
  • 40
  • 53
  • You probably want to compare `type()` in this case. – scharette Dec 22 '17 at 21:41
  • 3
    Usually a testing framework wil supply a function to test for exceptions, something like `assert_raises`. – Klaus D. Dec 22 '17 at 21:44
  • 1
    No, you'd have to use `try` if you wanted to manually catch the error; the function doesn't *return* the error, it *raises* it. – jonrsharpe Dec 22 '17 at 21:52
  • 1
    Assertions are mostly for checking program errors, those that imply program code changes to fix (that is bugs in the code, things that should neve happen, that's why `assert` only works if `__debug__` is True), not runtime errors or conditions that may or may not arise, or other special events. For those (think `Exceptions`) use a `try` block – progmatico Dec 22 '17 at 21:59

1 Answers1

1

See this: What is the use of "assert" in Python?

assert is for asserting a condition, means verify that this condition has been met else trigger an action. For your use case, you want to catch an exception, so this is something you want.

#!/usr/bin/env python
import sys
def get_value(x):
    lookup = {'one': 1}
    return lookup[x]

try:
  get_value('two')
except: # catch *all* exceptions
  e = sys.exc_info()
  print e

This will catch the exception and print it. In this particular case it will print something like: (<type 'exceptions.KeyError'>, KeyError('two',), <traceback object at 0x102c71c20>)

Ashutosh Bharti
  • 367
  • 2
  • 10