Logesh
Logesh

Reputation: 53

How to check which statement has thrown exception?

I have a statement like this.

I just want to know which of the two assert statement has thrown the exception.

try:
    assert re.search("xyz", statement)
    assert re.search("abc", statement)
except AssertionError:
    print "AssertionError : Expected Error message not found"

Thanks for the answer.

Upvotes: 0

Views: 125

Answers (4)

Joe
Joe

Reputation: 1

Maybe you want to differ the exceptions?Then Getting exception details in Python can help you. Copying the answer here:

import sys
try:
   assert re.search("xyz", statement)
   assert re.search("abc", statement)
except  AssertionError:
   type, value, traceback = sys.exc_info()

Then you can print out the info.

Upvotes: 0

vaultah
vaultah

Reputation: 46533

You could use functions from the traceback module. For example, extract_tb returns a list of tuples (named tuples in Python 3.5 and newer) representing the stack trace entries. Each tuple contains a line number as well as the source text line (if available).

import traceback

try:
    assert 1
    assert None
except AssertionError as e:
    for x in traceback.extract_tb(e.__traceback__, limit=-1):
        print(x.lineno, repr(x.line)) # Prints 5 'assert None'

Upvotes: 1

Klaus D.
Klaus D.

Reputation: 14369

You are able to print the last raised exception with traceback.print_exc(). An example:

>>> import traceback
>>> try:
...    a = 1 / 0
... except:
...    traceback.print_exc()
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zero

There is also traceback.format_exc() in case you don't want to print.

Upvotes: 0

PM 2Ring
PM 2Ring

Reputation: 55469

As mentioned in The assert statement docs, you can give an expression after the assertion test expression; that second expression will be passed in the AssertionError. Here's a simple demo:

for n in (-5, 10, 20):
    try:
        assert 0 <= n, '%d is too low' % n
        assert n <= 10, '%d is too high' % n
        print('%d is ok' % n)
    except AssertionError as err:
        print "AssertionError:", err

output

AssertionError: -5 is too low                                                                                                                  
10 is ok                                                                                                                                       
AssertionError: 20 is too high     

That second expression doesn't have to be a string, it can be anything. Since assertions should only be used to verify program logic, not to validate user data, I generally don't bother passing a nicely-formatted string, I just pass a tuple containing the relevant values, and maybe an identifying string. Eg,

assert (a * b > c), ('Bad product', a, b, c)

Upvotes: 1

Related Questions