5

Java 関数が決して返らない (つまり、常にスローする) ことをコンパイラ (注釈またはその他) に認識させる方法はありますか?

単純化/構成された例を次に示します。

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 例外を使用します。

于 2013-01-19T10:01:35.690 に答える