Assertion is a programming concept used while writing a code where the user declares a condition to be true using assert statement prior to running the module. If the condition is True, the control simply moves to the next line of code. In case if it is False the program stops running and returns AssertionError Exception.
The function of assert statement is the same irrespective of the language in which it is implemented, it is a language-independent concept, only the syntax varies with the programming language.
Syntax of assertion:
assert condition, error_message(optional)
Example 1: Assertion error with error_message.
Traceback (most recent call last): File "/home/bafc2f900d9791144fbf59f477cd4059.py", line 4, in assert y!=0, "Invalid Operation" # denominator can't be 0 AssertionError: Invalid Operation
The default exception handler in python will print the error_message written by the programmer, or else will just handle the error without any message.
Both of the ways are valid.
Handling AssertionError exception:
AssertionError is inherited from Exception class, when this exception occurs and raises AssertionError there are two ways to handle, either the user handles it or the default exception handler.
In Example 1 we have seen how the default exception handler does the work.
Now let’s dig into handling it manually.
Example 3: Testing a program.
Roots of the quadratic equation are : 2.0 3.0 Roots are imaginary Roots of the quadratic equation are : -3.0 -3.0
This is an example to show how this exception halts the execution of the program as soon as the assert condition is False.
Other useful applications :
- Checking values of parameters.
- Checking valid input/type.
- Detecting abuse of an interface by another programmer.
- Checking output of a function.
- Python | Mean Squared Error
- NZEC error in Python
- Python | 404 Error handling in Flask
- Floating point error in Python
- Python | Prompt for Password at Runtime and Termination with Error Message
- ML | Log Loss and Mean Squared Error
- ML | Mathematical explanation of RMSE and R-squared error
- Important differences between Python 2.x and Python 3.x with examples
- Reading Python File-Like Objects from C | Python
- Python | Index of Non-Zero elements in Python list
- Python | Convert list to Python array
- Python | Merge Python key values to list
- Python | Add Logging to a Python Script
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Add Logging to Python Libraries
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.