简体   繁体   中英

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?

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. And it uses a standard JDK exception , which is meant to be used in such situations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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