[英]Does not return java function annotation
Is there any way to force the compiler (annotation or othewise) to realize a java function is never returning (ie always throwing), so that subsequently it will not error out its usages as the last statement in other functions returning non void? 有什么方法可以迫使编译器(注释或其他方法)实现一个Java函数永不返回(即始终抛出),以便随后它不会将其用法作为其他函数中的最后一个语句返回non void的错误吗?
Here's a simplified/made-up example: 这是一个简化/虚构的示例:
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();
}
Thank you. 谢谢。
No, it's not possible. 不,不可能。
Note, however, that you can easily work it around as follows: 但是请注意,您可以按照以下步骤轻松解决它:
int add( int x, int y ) {
throw notImplemented();
}
Exception notImplemented() {
... some stuff here (generally logging, sometimes recovery, etc)
return new NotImplementedException();
}
Why not throw directly from the not implemented method? 为什么不直接从未实现的方法中抛出?
int add( int x, int y ) {
throw new UnsupportedOperationException("Not yet implemented");
}
This will compile fine even if the method does not return an int. 即使该方法不返回int,也可以正常编译。 And it uses a standard JDK exception , which is meant to be used in such situations.
并且它使用标准的JDK异常 ,该异常应在这种情况下使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.