What to do with never-occurring, useless exceptions?

I have this code:

HttpPut put = new HttpPut(url);
try {
    put.setEntity(new StringEntity(body, "UTF-8"));
} catch (UnsupportedEncodingException e1) {
    // That would really not be good
    e1.printStackTrace();
}

On a platform that is known to support this encoding.

The exception will never rise. I will never do anything.

The fact that the code still exists suggests that it is likely that this could happen, and that the rest of the code may be executed in an unreliable state. But it never will be. Or, if so, elegant network connections are the last of my problems.

So I have this ugly useless catch try block. What should I do with this?

(In this particular case, there is no other choice if I want to use StringEntity. String.getBytesFor example, it has a bunch of methods that take an object Charset, for example, avoiding the need to catch an exception, but not StringEntity)

+4
source share
1 answer

I would choose one RuntimeExceptionthat indicates that you think this should never happen. In this way:

  • If this ever happens, you will learn about it, rather than swallow it and continue.
  • Your expectation that this will never happen is clearly documented.

You can even create your own subclass RuntimeExceptionfor this:

// https://www.youtube.com/watch?v=OHVjs4aobqs
public class InconceivableException extends RuntimeException {
    public InconceivableException(String message) {
        super(message);
    }

    public InconceivableException(String message, Throwable cause) {
        super(message, cause);
    }
}

, catch, . :

public static HttpPut createHttpPutWithBody(String body) {
    HttpPut put = new HttpPut(url);
    try {
        put.setEntity(new StringEntity(body, "UTF-8"));
        return put;
    } catch (UnsupportedEncodingException e) {
        throw new InconceivableException("You keep using that encoding. "
            + "I do not think it means what you think it means.", e);
    }
}

createHttpPutWithBody , , "".

+11

All Articles