b10hazard
b10hazard

Reputation: 7809

Can "assert" be used to check for specific exceptions in a function?

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?

Upvotes: 1

Views: 61

Answers (1)

Ashutosh Bharti
Ashutosh Bharti

Reputation: 367

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>)

Upvotes: 1

Related Questions