try/except catches errors gracefully. else runs on success; finally always runs.
Raising Exceptions
raise ValueError("msg")
Custom Exceptions
Inherit from Exception to create custom error types.
try/except catches errors gracefully. else runs on success; finally always runs.
raise ValueError("msg")
Inherit from Exception to create custom error types.
try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero") except (ValueError, TypeError) as e: print(f"Error: {e}") else: print(f"Result: {result}") finally: print("Cleanup")
def divide(a, b): try: result = a / b except ZeroDivisionError: return "Cannot divide by zero" except TypeError: return "Invalid types" else: return f"Result: {result}" finally: print("Cleanup done") print(divide(10, 2)) print(divide(10, 0)) print(divide(10, "x")) # Custom exception class InsufficientFundsError(Exception): pass def withdraw(balance, amount): if amount > balance: raise InsufficientFundsError("Not enough funds") return balance - amount try: withdraw(100, 200) except InsufficientFundsError as e: print("Error:", e)
Create custom InvalidEmailError.
class InvalidEmailError(Exception): pass
def validate(email):
if "@" not in email: raise InvalidEmailError(email)
When does finally execute?
Finally always runs.
EAFP (try/except) is Pythonic for exceptional cases. LBYL (if check) for expected conditions.