Error Handling

20 min In Progress

Learning Objectives

  • Catch exceptions with try/except
  • Handle specific error types
  • Use finally for cleanup
  • Create custom exceptions

Try and Except

Wrap risky code in a try block and handle errors in except.

try:
    num = int(input("Enter a number: "))
    print(10 / num)
except ValueError:
    print("That was not a valid number.")
except ZeroDivisionError:
    print("Cannot divide by zero.")

Else and Finally

else runs if no exception occurs. finally always runs.

try:
    result = 10 / 2
except ZeroDivisionError:
    print("Error")
else:
    print(f"Result: {result}")
finally:
    print("Cleanup complete.")

Course Example: File Error Handling

Robust file reading with multiple exception types.

try:
    with open('input.txt', 'r') as f:
        for line in f:
            print(line)
except FileNotFoundError:
    print("Whoops! File does not exist.")
except Exception:
    print("Something unforeseen happened")
finally:
    print("I will always show up")

Course Example: Custom Exception

Define your own exception by inheriting from Exception.

class RecipeNotValidError(Exception):
    def __init__(self):
        self.message = "Your recipe is not valid"

try:
    raise RecipeNotValidError
except RecipeNotValidError as e:
    print(e.message)

📝 Exercise: Safe Division

Write a function safe_divide(a, b) that returns the result or an error message, handling ZeroDivisionError and TypeError.

code.py
Output

            
← Back to Chapter