Python UnicodeDecodeError Exception
Example
A UnicodeDecodeError occurs if bytes cannot be decoded:
data = b"\xff"
print(data.decode("utf-8"))
Try it Yourself »
Definition and Usage
The UnicodeDecodeError exception occurs when bytes cannot be decoded (changed to a string) with the given encoding.
In the example, the byte 0xff is never used in UTF-8, so it cannot be decoded.
Tip: Decode with the same encoding that was used to create the bytes. When you read a file, you can choose the encoding: open("file.txt", encoding="utf-8").
Exception Handling
Example
Handling the UnicodeDecodeError in a try...except statement:
data = b"\xff"
try:
print(data.decode("utf-8"))
except UnicodeDecodeError:
print("The bytes are not valid UTF-8")
Try it Yourself »
Related Pages
Read more about handling errors in our Python Try Except Tutorial.