java - 不返回 java 函数注解

标签 java throw

有什么方法可以强制编译器(注释或其他方式)实现 java 函数永远不会返回(即总是抛出),以便随后它不会错误地使用它作为其他返回非 void 函数的最后一条语句?

这是一个简化/编造的例子:

int add( int x, int y ) {
    throwNotImplemented();  // compiler error here: no return value.
}

// How can I annotate (or change) this function, so compiling add will not yield
// an error since this function always throws?
void throwNotImplemented() {
    ... some stuff here (generally logging, sometimes recovery, etc)
    throw new NotImplementedException();
}

谢谢。

最佳答案

不,这不可能。

但是请注意,您可以按如下方式轻松解决此问题:

int add( int x, int y ) {
    throw notImplemented();
}

Exception notImplemented() {
    ... some stuff here (generally logging, sometimes recovery, etc)
    return new NotImplementedException();
}

关于java - 不返回 java 函数注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14413131/

相关文章:

java - 我如何使 JLabel 文本自动更改?

java - 使用 Betamax 时为 "Illegal use of nonvirtual function call"

sql-server - T-SQL 抛出异常

c++ - 在修改后的异常上使用 `throw;`

Java:最终特朗普如何抛出?

java - 将 List<BufferedImage> 转换为图像

java - 为什么 Java 提示我的 try-with-resources block ?

java - 将 SSL 证书导入 Java

c++ - 如果我尝试在 C++ 中的 catch block 中抛出一些东西,为什么会导致终止

c# - 通用扩展方法中的代码契约与 if