To withstand or throw exceptions that can never happen?

Say I have the following line in a method:

 String encodedString = URLEncoder.encode(foo, "utf-8");

this method produces UnsupportedEncodingException. What's better:

/** @throws UnsupportedEncodingException umm...never
 */
public void myMethod() throws UnsupportedEncodingException {
   ...
   String encodedString = URLEncoder.encode(foo, "utf-8");
   ...
}

(causing the caller to catch it himself) Or:

public void myMethod() {
   try {
     ...
     String encodedString = URLEncoder.encode(foo, "utf-8");
     ...
   catch(UnsupportedEncodingException e) {
      Logger.log("cosmic ray detected!");
   }

}

Or is there a more elegant way to handle exceptions that never actually occur?

+5
source share
2 answers

Never say never;)

In the above example, you can always catch an exception and then throw a RuntimeException:

public void myMethod() {
   try {
      ...
      String encodedString = URLEncoder.encode(foo, "utf-8");
       ...
   } catch(UnsupportedEncodingException e) {
     throw new RuntimeException("This should not be possible",e);
   }

}

, -, , 99,999%, , , , , , , , .

+17

, , , , , , .

, - , , . , throws API.

, (Effective Java 2nd Edition, 61). , - , , .

+5

All Articles