SyntaxStudy
Sign Up
Python Intermediate 9 min read

Error Handling

Error Handling in Python

try / except

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
except (TypeError, ValueError) as e:
    print(f"Type/Value error: {e}")
except Exception as e:
    print(f"Unexpected: {e}")
else:
    print("No error occurred")
finally:
    print("Always runs")

Raising Exceptions

def divide(a, b):
    if b == 0:
        raise ValueError("Divisor cannot be zero")
    return a / b

Custom Exceptions

class AppError(Exception):
    pass

raise AppError("Something went wrong")
Pro Tip

Catch specific exceptions first — broad except Exception should be a last resort.