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

Raising Exceptions

Cost of Raising an Exception

Last updated