Java, what is the advantage of Throwing RuntimeException

What is the advantage of declaring (Unchecked Exception) throws an exception based on the signature of the b / c method, this does not cause the caller to remain in the 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(); } 
+2
source share
4 answers

if you select an arbitrary excluded exception, it becomes more significant, but rather excludes the system exception, and the excluded exception does not make it catch.

0
source

It still serves as documentation, especially if you are not using a general RuntimeException, but something more specific like IllegalArgumentException or UnsupportedOperationException or IndexOutOfBoundsException , and also add some JavaDoc as to when this will happen.

In your code snippet, this is pretty pointless.

+3
source

This declaration is a signal to a developer who uses this code that raises a RuntimeException. But it does not smell good.

PS The code you sent will not compile:

 throw RuntimeException 

This is the wrong throw.

+2
source

The advantage is that usually the caller has nothing to do with exception. He catches it, wraps it with another exception, and throws it again. Or, conversely, it throws exception using the throws keyword and becomes transparent to this type if the exception is thrown.

I would say that the described situation is typical for applications where we usually write business code and have one centralized place that handles all exceptions. This is not true for the API. For example, if you use a library that implements SSH, you expect it to throw an IOException (or even a more specialized exception) when something goes wrong.

+1
source

Source: https://habr.com/ru/post/1233153/


All Articles