开发者

method implementation for this case in Java

I just saw a code snippet like this:

private static clas开发者_开发百科s DefaultErrorHandler<RT> implements ErrorHandler<RT> {
  public RT handle(Object[] params, Throwable e) {
   return Exceptions.throwUncheckedException(e);
  }
}

Now I am wondering what the static method throwUncheckedException (Throwable e) would return exactly and how it might be implemented regarding the generics.

Can anybody give me an example ?


You would define the method like this:

public static <T> T throwUncheckedException (Throwable e) { ... }

which essentially means "for any type T, return it". Then you rely on the compiler's ability to guess that T = RT.

I think the idea of returning a value from the throwUncheckedException method is as follows: you want to call a method that always throws a run-time exception, and you call it from a non-void method. Java compiler complains that the caller needs a return statement at the end of every execution branch. This trick saves you the need for a "dummy return".


I would have to guess that it consists of :

throw new RuntimeException(e);

but really, I'm guessing that the return value is just for show. The method is called 'throw'.

If it returns something, it returns something of type 'RT', whatever that is.


Having the method throwUncheckedException() returning something avoids an extra line in a calling method that needs a return value.

Had the exception been thrown directly from the handle method as follows:

public RT handle(Object[] params, Throwable e) {
    throw new RuntimeException(e);
}

The return statement would not have been needed (it would even have been illegal actually) because the compiler would be able to know that any statement following the throw would be unreachable.

But since the throw is done in another method, and since a return value is required for the handle method, a return statememt must be added.

Having the throwUncheckedException() return something allows the call to be in the return statement.

The throwUncheckedException() must be something close to:

public static <T> T throwUncheckedException(Throwable e) {
    throw new RuntimeException(e);
    return null;
}

IMHO, the fact that this raised your question shows that it is too puzzling to be worthy. Perhaps a better way to achieve the same goal would be something like this:

public RT handle(Object[] params, Throwable e) {
    throw Exceptions.makeUncheckedException(e);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜