在运行时执行“健全性检查”时,最好的内置是什么 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());
}
}
我想更具体的表达这个问题的方法是“如果在生产环境中存在永远不应该到达但已到达的代码,我应该抛出什么样的异常?”这并不完全是正确的问题,但所有“健全性检查”都可以用永远不应该到达的代码来“拼写”,因此它足够接近。
最佳答案
Java 是面向对象的。
抛出 SanityException
或 FailedSanityCheckException
。
换句话说,创建您自己的扩展 Exception 的类。
也许MyCompanyException比SanityException更合适;)
如果您希望它是未经检查的运行时异常,请扩展 RuntimeException :
class SanityException extends RuntimeException {
public SanityException(String msg) {
super(msg);
}
}
它非常简单而且非常强大。
你的逻辑只能捕获和处理SanityExceptions,这很好。
我知道您的问题要求内置异常...但是如果您发现内置选项令人厌恶因为它们不够具体,那么这就是创建您自己的异常的确切原因(特别是考虑到它是多么容易)。
在我看来,这就是异常的使用方式。
关于java - 抛出以指示失败 "sanity check"的最佳内置 JRE 异常是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17356811/