実行時に「健全性チェック」を実行する場合Exception
、論理エラーを示すためにスローするのに最適な組み込みは何ですか? InternalError
魅力的ですが、Error
私の理解では、アプリケーションロジックエラーではなく、JVM 自体の問題を示すためにのみ使用する必要があります。今はRuntimeException
s を投げがちですが、型が一般的すぎて嫌です。使用すべきより具体的なタイプはありますか?
assert
これらのチェックは本番環境で実行する必要があるため、使用を避けています。このため、「使用する必要がありますassert
」は正解ではありません。
この質問の主観的な性質をお詫びしますが、私が気付いていないよく知られているベストプラクティスがいくつかあることを願っています.
編集:これは私が話していることの良い例ですが、確かに他の良い例があり、アイデアはより一般的です:
public static void foobar(ModelObject o) {
switch(o.getEnumProperty()) {
case ENUMVALUE1:
// Handle...
break;
case ENUMVALUE2:
// Handle...
break;
default:
// In theory, this should never be reached. The code should handle any
// enum value it's Java-legal for the code to pass. But, if a new
// enum value is added and this code is not updated, this WILL be
// reached. This is not an IllegalArgumentException because the caller
// passed a valid value -- remember, we SHOULD handle any enum value
// here -- but the code has not been updated. For this reason, it's an
// "internal error" of sorts. However, there's no good "my program's
// logic is broken" Exception that I know of built into the JRE. It is
// this Exception that I'm looking for in this question.
//
// Hopefully this clarifies the question somewhat.
throw new RuntimeException("Unhandled: "+o.getType());
}
}
この質問をより具体的に表現する方法は、「本番環境で、決して到達してはならないが GETS に到達するコードがある場合、どのような種類の例外をスローする必要がありますか?」ということになると思います。これは正確には正しい質問ではありませんが、すべての「サニティ チェック」は、絶対に到達してはならないコードに関して「綴る」ことができるため、十分に近いものです。