try — Intermediate Examples
Starts a block of code that will be monitored for exceptions
Try/except/else/finally
The complete error handling pattern.
python
def divide(a, b): try: result = a / b except ZeroDivisionError: print("Error: division by zero") return None except TypeError as e: print(f"Type error: {e}") return None else: print(f"Success: {a}/{b} = {result}") return result finally: print("Cleanup complete") divide(10, 3) print() divide(10, 0) print() divide("10", 3)
else runs only if no exception was raised. finally always runs, even if an exception occurs or the function returns. Use finally for cleanup.
Want to try these examples interactively?
Open Intermediate Playground