这是我的解决方案——为 Android 开发,但可以轻松适应“常规”Java:
public class ImpossibleException extends RuntimeException {
public ImpossibleException(@NonNull String whyNotPossible) {
this(whyNotPossible, null);
}
public ImpossibleException(@NonNull String whyNotPossible, Throwable throwable) {
super("Impossible exception: " + whyNotPossible, throwable);
Log.e("Impossible", whyNotPossible, throwable);
}
}
用法:
try {
byte[] data = "Hello".getBytes("utf-8");
Log.i("Test", "data.length=" + data.length);
} catch (UnsupportedEncodingException e) {
throw new ImpossibleException("Android always supports utf-8", e);
}
构造whyNotPossible
函数意味着不需要在错误发生的地方记录错误,也不需要注释。
我想这应该是一个ImpossibleException extends RuntimeException
还是一个ImpossibleError extends Error
。