Error Handling

Exception

  • An exception is a kind of error that terminates the execution of a program

  • Handling is important, otherwise, code will terminate in case of any exception

numbers = [1, 2]
print(numbers[2]) # it will throw an error, list index out of range

age = int(input("age: ")) # it will throw an error
# alphabets/words can not be converted to numbers

Handling Exception

try:
    age = int(input("age: "))
    print(age)
except ValueError as e:
    print("You didn't enter a valid age")
    print(e) # it will print the error as well, important for debug
#     print(type(x))
else:
    print("No Exceptions were thrown")
print("Execution Continues")

Handling Different Exceptions

# This is one type of exception here, valueError
# You can search of many similar exceptions whenever there is a need

try:
    age = int(input("age: "))
    print(age)
    xfactor = 10/ age
except (ValueError,ZeroDivisionError):
    print("You didn't enter a valid age")
else:
    print("No Exceptions were thrown")
print("Execution Continues")

Raising Exceptions

def calculate_xfactor(age):
    if age <=0:
        raise ValueError("Age can not be 0 or less than zero")
    return 10/age

try:
    calculate_xfactor(0)
except ValueError as error:
    print(error)
    
# output: Age can not be 0 or less than zero

Cost of Raising an Exception

from timeit import timeit

code1 = """
def calculate_xfactor(age):
    if age <=0:
        raise ValueError("Age can not be 0 or less than zero")
    return 10/age


try:
    calculate_xfactor(0)
except ValueError as error:
    #print(error)
    pass
"""
print("Time of execution of code1",timeit(code1,number = 10000))

code2= """
def calculate_xfactor(age):
    if age <=0:
        return None
    return 10/age
    

xfactor = calculate_xfactor(0)
if xfactor == None:
    pass
"""
print("Time of execution of code2",timeit(code1,number = 10000))

# Output for the code will be:
# Time of execution of code1 0.011037113996280823
# Time of execution of code2 0.012951454998983536

# Hence raising an exception takes relative longer time

Last updated

Was this helpful?