Quick Answer
Handle unsupported character encoding issues.
Understanding the Issue
This checked exception occurs when an unsupported character encoding is specified for string encoding/decoding operations.
The Problem
This code demonstrates the issue:
Java
Error
String text = "hello";
byte[] bytes = text.getBytes("UTF-32"); // May throw
The Solution
Here's the corrected code:
Java
Fixed
// Solution 1: Use standard charset names
try {
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
} catch (UnsupportedEncodingException e) {
// Will never happen for StandardCharsets
}
// Solution 2: Check supported charsets
if (Charset.isSupported("UTF-32")) {
byte[] bytes = text.getBytes("UTF-32");
}
// Solution 3: Default encoding with fallback
String encoding = "UTF-32";
try {
return new String(bytes, encoding);
} catch (UnsupportedEncodingException e) {
return new String(bytes); // Default charset
}
// Solution 4: Java 7+ Files methods automatically handle encoding
Files.readAllLines(path, StandardCharsets.UTF_8);
Key Takeaways
Prefer StandardCharsets constants and validate encodings when needed.