try — Advanced Playground
Starts a block of code that will be monitored for exceptions
Python Playground
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__}")
Output
Click "Run" to execute your code
'raise X from Y' sets __cause__ for explicit chaining. __context__ is set automatically when an exception occurs while handling another.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?