What is Assertion in Python?
Assertion is use in programming language to declare condition which should be validate as true by using assert statement prior to running the module or line of code. If assert condition is true then program control moves to next line in case it’s false the program stops running and throw Python AssertionError exception.
Python Syntax of Assertion
assert condition, error_message(optional)
Where to use Assertion?
In Python, Assertion can be use in following cases:
- Checking valid input/type.
- Checking values of parameters.
- Detecting abuse of an interface by another programmer.
- Checking output of a function.
Python AssertionError Example
x = 10 z = 0 # denominator can't be 0 assert z != 0, "Invalid Operation" print(x / z)
Traceback (most recent call last): File "/home/xyz.py", line 4, in assert z!=0, "Invalid Operation" AssertionError: Invalid Operation
In this above Python program, The default exception handler will print the error message written by the programmer, or else will just handle the error without any message.
Solution AssertionError exception
AssertionError is subclass of Exception class, when this exception AssertionError occurs in program there are two ways to handle, either default exception handler or user handle it.
try: x = 10 z = 0 assert z != 0, "Invalid Operation" print(x / z) #The configured error message will print in log except AssertionError as err: print(err)
In this topic you learn about the Assertion in programming language and how to use it. In case any Python AssertionError occurs then you can handle it through Try-except exception handling.