Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What to do with never happening, 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 that encoding.

The exception is never going to be raised. I will never do anything about it.

The fact that the code is there still suggests that there is a chance that it may happen, and that the rest of the code could be executed in an unreliable state. But it will never. Or if it does, graceful network connections fallback is the last of my problems.

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

(In this specific case, there is not much other choice if I want to use StringEntity. String.getBytes for example has a bunch of methods that would accept a Charset object, for instance, avoiding the need to catch the exception, but not StringEntity)

like image 776
njzk2 Avatar asked Dec 19 '22 12:12

njzk2


1 Answers

I would throw some kind of RuntimeException which indicates that you think this really should never happen. That way:

  • If it ever does happen, you find out about it rather than swallowing it and continuing
  • Your expectation that it really can never happen is clearly documented

You could even create your own subclass of RuntimeException for precisely 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);
    }
}

You might also want to encapsulate the operation into a separate method, so that you don't get such catch blocks populating your code. For example:

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);
    }
}

Then you can call createHttpPutWithBody wherever you'd need to, and keep your main code "catch clean".

like image 76
Jon Skeet Avatar answered Jan 02 '23 17:01

Jon Skeet