Python | Confirmation error

Python Methods and Functions

Assertion syntax:
assert status, error_message (optional)

Example 1: Assertion failed with error message.

# AssertionError with error_message.

x = 1

y = 0

assert y! = 0 , " Invalid Operation " # denominator cannot be 0

print (x / y)

Output:

 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 just handle the error without any message. 
Both methods are valid.

Handling AssertionError:
AssertionError inherits from Exception class when this exception is thrown and raises AssertionError , there are two ways to handle it, either the user handles it or the default exception handler. 
In Example 1, we saw how the default exception handler works. 
Now let's dive into manual processing.

Example 2

# Handling

try :

  x = 1

y = 0

assert y! = 0 , "Invalid Operation "

  print (x / y) < / p>

 
# user-supplied errror_message is printed

except AssertionError as msg: 

print (msg)

Exit:

 Invalid Operation 

Practical application.
Example 3: Testing the program.

# Quadratic roots

import math

def ShridharAcharya (a, b, c):

try :  

assert a! = 0 , "Not a quadratic equation as cofficient of x ^ 2 can't be 0 "

  D = (b * b - 4 * a * c)

assert D & gt; = 0 , "Roots are imaginary"

r1 = ( - b + math.sqrt (D)) / ( 2 * a)

r2 = ( - b - math.sqrt (D)) / ( 2 * a)

  print ( "Roots of the quadratic equation are:" , r1, "", r2)

  except AssertionError as msg:

  print (msg)

ShridharAcharya ( - 1 , 5 , - 6 )

ShridharAcharya ( 1 , 1 , 6 )

ShridharAcharya ( 2 , 12 , 18 )

Output:  

 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 showing how this exception stops program execution, like only the assertion condition is false. 

Other useful applications:

  • Validate parameter values.
  • Validate input / type.
  • Interface abuse detected by another programmer.
  • Function output check.





Tutorials