Lesson 12 of 15

Error Handling

Error Handling

Python uses exceptions for error handling. Exceptions are classes that inherit from BaseException.

try / except

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

Multiple except Clauses

try:
    value = int("abc")
except ValueError as e:
    print(f"ValueError: {e}")
except TypeError:
    print("Wrong type")

else and finally

try:
    result = 10 / 2
except ZeroDivisionError:
    print("error")
else:
    print(f"ok: {result}")  # runs only if no exception
finally:
    print("always runs")    # cleanup code

Raising Exceptions

def set_age(age):
    if age < 0:
        raise ValueError(f"Age cannot be negative: {age}")
    return age

Custom Exceptions

class InsufficientFundsError(Exception):
    def __init__(self, amount, balance):
        super().__init__(f"Need {amount}, have {balance}")
        self.amount = amount
        self.balance = balance

Your Task

Implement safe_divide(a, b) that:

  • Returns a / b if b != 0
  • Raises ValueError("Cannot divide by zero") if b == 0
Pyodide loading...
Loading...
Click "Run" to execute your code.