Python UnicodeError Exception
Example
Catch any Unicode error with UnicodeError:
text = "caf\u00e9"
try:
print(text.encode("ascii"))
except UnicodeError:
print("The text could not be encoded")
Try it Yourself »
Definition and Usage
The UnicodeError exception is the base class for the errors that occur when text is encoded or decoded (changed to or from bytes).
It has three child classes: UnicodeEncodeError, UnicodeDecodeError and UnicodeTranslateError. except UnicodeError catches all of them.
In the example, "caf\u00e9" is the word café. The letter é does not exist in ASCII, so encode() raises a UnicodeEncodeError.
Related Pages
Read more about handling errors in our Python Try Except Tutorial.