📙
Python Programming
  • Python Programming
  • Installation and Setup
  • Part 1: Basics
    • Variables
      • Primitive Data Types
      • Secondary Data Types
    • Control Flow and Loop
    • Functions
    • Error Handling
    • Decorators
    • Constructor
    • Built-in Functions and Modules
    • Pythonic Code
    • Miscellaneous Functionalities
    • Understanding Checkpoint I
    • Python Problem Practice I
      • Solutions
  • Part 2: Level Up
    • Real Life Application I
    • Real Life Application II
    • OOP Concepts
    • Creating Library
    • Real Life Application III
  • Processing Related
    • Parallel Processing
    • Oreilly - High Performance Python
    • Memory Management
      • Memory Leak
      • String
      • Array
      • Dictionary
    • Ubuntu CPU and RAM
    • Time and Space Complexity
  • Data Structure
    • Data Structure Overview
    • Array
    • Stack
    • Queue
    • LinkedList
    • Hash-table and Hash-map
    • Recursion
    • Binary Tree
    • Heap Data Structure
    • Graphs
      • Python Graph Visualisation
    • Dynamic Programming
    • Problem Solving Techniques
    • Additional topics
Powered by GitBook
On this page
  1. Part 1: Basics

Error Handling

PreviousFunctionsNextDecorators

Last updated 4 years ago

Was this helpful?

CtrlK
  • Exception
  • Handling Exception
  • Handling Different Exceptions
  • Raising Exceptions
  • Cost of Raising an Exception

Was this helpful?

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) 

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
# it will print the error as well, important for debug
# print(type(x))
else:
print("No Exceptions were thrown")
print("Execution Continues")