UnicodeEncodeError — Advanced Playground
Raised when encoding a string to bytes fails
Python Playground
# Custom exception hierarchy
class DetailedUnicodeEncodeError(UnicodeEncodeError):
def __init__(self, message, details=None):
super().__init__(message)
self.details = details or {}
def __str__(self):
base = super().__str__()
if self.details:
detail_str = ", ".join(f"{k}={v}" for k, v in self.details.items())
return f"{base} [{detail_str}]"
return base
try:
raise DetailedUnicodeEncodeError(
"Something went wrong",
{"code": 42, "source": "test"}
)
except UnicodeEncodeError as e:
print(f"Caught: {e}")
if hasattr(e, 'details'):
print(f"Details: {e.details}")
Output
Click "Run" to execute your code
Custom exception subclasses let you add context and structure to your error handling.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?