简体   繁体   中英

Refactor method to throw at most one checked exception instead of ExecutionException and InterruptedException

I have a method like

public void methodName() throws ExecutionException, InterruptedException {}

SonarQube raises an issue on this method, suggesting to refactor this code.

If I replace those exceptions with Exception (which both of them extend), then it says throwing Exception is too generic.

How can I resolve this issue?

Exact sonarQube message: Refactor this method to throw atmost one checked exception instead of ExecutionException , InterruptedException

Detailed Hint by sonarQube: https://sbforge.org/sonar/rules/show/squid:S1160?layout=false

I don't really have the answer for you, but I guess it might be worth looking more in depth at the Exceptions. I looked up the following definitions on docs.oracle.com:

ExecutionException: Exception thrown when attempting to retrieve the result of a task that aborted by throwing an exception. This exception can be inspected using the Throwable.getCause() method.

InteruptedException: Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity. Occasionally a method may wish to test whether the current thread has been interrupted, and if so, to immediately throw this exception. The following code can be used to achieve this effect: if (Thread.interrupted()) // Clears interrupted status! throw new InterruptedException();

That being said, maybe the nature of the ExecutionException means that we don't have to worry about catching the InteruptedException (since an ExcecutionException is thrown when mishandling another thrown exception). So maybe we try something like this:

public void methodName() throws ExecutionException {}

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