5

有什么方法可以强制编译器(注解或其他方式)实现 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();
}

谢谢你。

4

2 回答 2

7

不,这是不可能的。

但是请注意,您可以轻松地解决它,如下所示:

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

Exception notImplemented() {
    ... some stuff here (generally logging, sometimes recovery, etc)
    return new NotImplementedException();
}
于 2013-01-19T10:02:28.887 回答
0

为什么不直接从未实现的方法中抛出?

int add( int x, int y ) {
    throw new UnsupportedOperationException("Not yet implemented");
}

即使该方法不返回 int,这也将编译得很好。并且它使用标准的 JDK exception,这意味着在这种情况下使用。

于 2013-01-19T10:01:35.690 回答