Python AssertionError Exception
Example
An AssertionError
is raised when the assert statement fails:
x = "hello"
#if condition returns True, then nothing happens:
assert x == "hello"
#if condition returns False, AssertionError is raised:
assert x == "goodbye"
Try it Yourself »
Definition and Usage
The AssertionError
exception occurs when an assert statement fails.
You can handle the AssertionError
in a try...except
statement, see the example below.
Read more about the assert keyword in our assert Keyword chapter.
Exception Handling
Example
Handling the AssertionError
in a try...except
statement:
x = "hello"
try:
assert x == "goodbye"
except AssertionError:
print("Error in assert statement")
except:
print("Something else went wrong")
Try it Yourself »