Assertions in programming are statements used to verify that a certain condition is met. For example an assertion can be used to validate the correctness of an expression or calculation.

Assertions act like program's internal self-checks, they indicate whenever there is a  flaw in the program's logic.

In Python, assertions are made using the  assert keyword.

assert <condition>, <display message>
condition The condition to be asserted. If this condition is not met an assertion error is raised
display message An optional string that will be displayed as a custom error message if the assertion fails.
def div(a, b):
   #This asserts that the value of b is not zero.
   assert b != 0, "b should never be zero."
   
   return a / b

print(div(10, 5))

AssertionError exceptions are  raised when an assertion expression is evaluated to a False boolean value.

def div(a, b):
   #This asserts that the value of b is not zero.
   assert b != 0, "b should never be zero."
   
   return a / b

print(div(10, 0))

When a program raises an AssertionError, it indicates that something has gone wrong in the execution logic.

Handling the AssertionError

When an AssertionError exception is encountered in Python, it means that a condition that the program evaluated has failed. To handle this exception, you should examine the code where the exception has occurred and debug it. This usually involves examining the values of variables involved in the assertion statement, as well as any related code.

You can also use a debugging tool such as a breakpoint or a stack trace to help identify and fix the cause of the assertion failure. Once the root cause of the exception is identified and fixed, the program should be able to resume without the exception being raised again.

The try-except blocks can also be used to catch AssertionError exceptions.  This is useful for debugging purposes, as it allows the program to detect when an assertion fails and handle it accordingly.

import math

def square_root(num):
    
    assert num >= 0, "The number entered is negative"

    return math.sqrt(num)
 
num = -10   
try:
     square_root(num)
except AssertionError as e:
     #Use the absolute value of 'num'
     print(square_root(abs(num)))