Error Handling

What is Exception?

  • Runtime error that occurs during program execution.
  • If exception is not handled, it will cause program to crash.
  • Exception has to be handled to ensure smooth execution of program.
  • There are four blocks in handling exceptions.
  • Exception Blocks
    1. try: Contains code that may raise an exception.
    2. except: Contains code to handle the exception if it occurs.
    3. else: Contains code that will execute if no exception occurs.
    4. finally: Contains code that will execute regardless of occurrence of an exception.

Syntax for Exception Handling

  • try: # Code that may raise an exception except ExceptionType1: # Code to handle ExceptionType1 except ExceptionType2: # Code to handle ExceptionType2 except Exception as e: # Code to handle any exception else: # Code to execute if no exception occurs finally: # Code to execute regardless of exception occurrence

Exception Handling Example

  • try: user_input = input("Enter two number separated by ',': ") num_1, num_2 = map(float, user_input.split(',')) print(f"{num_1} / {num_2}: {num_1 / num_2}") except ZeroDivisionError: print("Error: Cannot divide by zero") except ValueError: print("Error: Invalid input. Please enter a number.") except Exception as e: print(f"Other Error: {e}") else: print("Division performed successfully") finally: print("Execution completed")

Common Exceptions

Exception ClassCause of ExceptionExample
ZeroDivisionErrorSecond operand of division or modulo operation is zero.10 / 0, 5 % 0
TypeErrorOperation is applied to an object of inappropriate data type.5 + "5", len(5)
ValueErrorFunction receives value with correct type but wrong value.int("abc"), float("xyz")
KeyErrorDictionary key is not found.my_dict = {"a": 1}; print(my_dict["b"])
IndexErrorSequence index is out of range.my_list = [1, 2, 3]; print(my_list[5])
NameErrorVariable is not defined.print(x) without defining x
AssertionErrorAssert statement fails.assert 2 + 2 == 5

Assertion

  • Used to test and ensure a condition is true.
  • Takes Boolean expression as input. If it evaluates to False, it raises an AssertionError.
  • Optionally, we can provide an error message as well.
  • Syntax: assert condition, "Error message"
  • Example:
    1. assert 2 + 2 == 4, "Broken Math" # No error assert 2 + 2 == 5, "Broken Math" # AssertionError with message "Broken Math"
    2. user_age = int(input("Enter your age: ")) assert user_age >= 18, "You must be at 18+" # To ensure age is never below 18

Assertion Examples

  • def calculate_area_of_rectangle(length, width): assert length > 0, "Length must be positive number" assert width > 0, "Width must be positive number" return length * width # Example usage: area = calculate_area_of_rectangle(5, 2) print(f"Area of rectangle: {area}") # Example usage with negative values: area = calculate_area_of_rectangle(-5, 2) print(f"Area of rectangle: {area}")

Raising Generic Exceptions

  • Allows us to force error based on condition
  • We can raise generic exceptions using raise keyword.
  • Syntax: raise ExceptionType("Error message")
  • Example:
    1. def check_license_eligibility(age): if type(age) != int: raise TypeError("Age must be an integer") if age < 0: raise ValueError("Age cannot be negative") if age > 16: return "Eligible" else: return "Not eligible" # Example usage: print(check_license_eligibility(18)) # Eligible for license print(check_license_eligibility(15)) # Not eligible for license print(check_license_eligibility(-5)) # Raises ValueError print(check_license_eligibility("twenty")) # Raises TypeError

Error Handling Techniques

  • Use specific exception types to handle known errors.
  • Use try-except block to handle exceptions.
  • Use finally block to ensure code is executed regardless of an exception occurrence.
  • Position of try-except block is important on exception handling.
  • Example:
    1. num_list = [10, 15, '20', 30] for num in num_list: try: print(num / 2) except Exception as e: print(f"Error on dividing {num}. \nError Message: {e}")num_list = [10, 15, '20', 30] try: for num in num_list: print(num / 2) except Exception as e: print(f"Error occurred for {num}. \nError Message: {e}")