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?

4
  • You probably want to compare type() in this case. Commented Dec 22, 2017 at 21:41
  • 3
    Usually a testing framework wil supply a function to test for exceptions, something like assert_raises. Commented Dec 22, 2017 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. Commented Dec 22, 2017 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 Commented Dec 22, 2017 at 21:59

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.