try — Advanced Examples
Starts a block of code that will be monitored for exceptions
Exception chaining and context
Using 'raise from' and understanding __cause__.
python
class DatabaseError(Exception): pass class ConnectionError(DatabaseError): pass def connect(host): try: if host == "bad": raise OSError(f"Cannot reach {host}") except OSError as e: raise ConnectionError(f"Database connection failed") from e try: connect("bad") except ConnectionError as e: print(f"Caught: {e}") print(f"Caused by: {e.__cause__}") print(f"Context: {e.__context__}")
'raise X from Y' sets __cause__ for explicit chaining. __context__ is set automatically when an exception occurs while handling another.
Want to try these examples interactively?
Open Advanced Playground