Java what is the benefit of Throwing RuntimeException

What is the benefit of declaring (Unchecked Exception)throws exception along method signature b/c it does not force caller to keep in try catch block.

public void testRuntimeEx()throws RuntimeException{ if(1==1){throw new RuntimeException()} } //Caller method public void testCaller(){ // not necessery to handle even caller does not known which RuntimeException might be throws then what is the benefit throws clause with method signature testRuntimeEx(); }

Answer1:

It still serves as documentation, especially if you do not use a generic RuntimeException, but something more specific like IllegalArgumentException or UnsupportedOperationException or IndexOutOfBoundsException and also add some JavaDoc as to when that would happen.

In your example code snippet, it is pretty meaningless, though.

Answer2:

This declaring is a signal for developer who uses this code, that it throws RuntimeException. But it doesn't smell good.

P.S. Code you posted will not compile:

throw RuntimeException

This is not correct throwing.

Answer3:

The benefit is that typically caller does not have anything to do with the exception. It catches it, wraps with other exception and throws again. Or, alternatively, declares the exception using throws keyword and becomes transparent for this type if exception.

I'd say that the described situation is typical for applications where we usually write business code and have one centralized place that handles all exceptions. It is not correct for APIs. For example if you are using library that implements SSH you are expecting it to throw IOException (or even more specialize exception) when something is going wrong.

Answer4:

if you throw custom unchecked exception it becomes more meaningfull rather catching system exception and unchecked exception does not force to catch too.

人吐槽 人点赞

Recommend

Comment

用户名: 密码:
验证码: 匿名发表

你可以使用这些语言

查看评论:Java what is the benefit of Throwing RuntimeException