怎么做从未发生过,无用的例外?

njz*_*zk2 4 java android character-encoding androidhttpclient

我有这个代码:

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

在已知支持该编码的平台上.

永远不会提出异常.我永远不会做任何事情.

代码存在的事实仍然表明它可能会发生,并且其余代码可能以不可靠的状态执行.但它永远不会.或者如果是这样,优雅的网络连接回退是我的最后一个问题.

所以我有这个丑陋无用的尝试catch块.我该怎么办?

(在这个特定情况下,如果我想使用它,没有太多其他选择StringEntity.String.getBytes例如,有一堆方法可以接受一个Charset对象,例如,避免需要捕获异常,但不是StringEntity)

Jon*_*eet 11

我会抛出一些RuntimeException表明你认为这真的不应该发生的东西.那样:

  • 如果它确实发生过,你会发现它而不是吞下它并继续下去
  • 您的期望,它真的可以永远不会发生的明确记载

您甚至可以RuntimeException为此创建自己的子类:

// 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

您可能希望将操作封装到单独的方法中,这样您就不会获得填充代码的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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以createHttpPutWithBody在任何你需要的地方打电话,并保持你的主要代码"抓住干净".