繁体   English   中英

不返回Java函数注释

[英]Does not return java function annotation

有什么方法可以迫使编译器(注释或其他方法)实现一个Java函数永不返回(即始终抛出),以便随后它不会将其用法作为其他函数中的最后一个语句返回non 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();
}

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

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

即使该方法不返回int,也可以正常编译。 并且它使用标准的JDK异常 ,该异常应在这种情况下使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM