2023-05-03 11:06:20 +02:00
|
|
|
== Why is this an issue?
|
|
|
|
|
2021-06-08 14:23:48 +02:00
|
|
|
Catching an exception only to immediately rethrow it without doing anything else is useless and misleading.
|
|
|
|
|
|
|
|
|
2023-05-03 11:06:20 +02:00
|
|
|
=== Noncompliant code example
|
2021-06-08 14:23:48 +02:00
|
|
|
|
2022-02-04 17:28:24 +01:00
|
|
|
[source,text]
|
2021-06-08 14:23:48 +02:00
|
|
|
----
|
|
|
|
try {
|
|
|
|
/* ... */
|
|
|
|
} catch (Exception e) { // Non-Compliant
|
|
|
|
throw e;
|
|
|
|
}
|
|
|
|
----
|
|
|
|
|
|
|
|
|
2023-05-03 11:06:20 +02:00
|
|
|
=== Exceptions
|
2021-06-08 14:23:48 +02:00
|
|
|
|
|
|
|
When all instances of a general exception must be handled, but some specific ones not, propagation must be used and so is allowed by this rule.
|
|
|
|
|
|
|
|
|
2023-05-25 14:18:12 +02:00
|
|
|
[source,text]
|
2021-06-08 14:23:48 +02:00
|
|
|
----
|
|
|
|
try {
|
|
|
|
/* ... */
|
|
|
|
} catch (RuntimeException e) { // Compliant - propagation of the unchecked exception
|
|
|
|
throw e;
|
|
|
|
} catch (Exception e) { // Compliant - catching of the checked exception
|
|
|
|
LOGGER.error("...", e);
|
|
|
|
}
|
|
|
|
----
|
|
|
|
|
|
|
|
Throwing the same exception can also makes sense when an action is done before throwing it again.
|
|
|
|
|
2023-05-25 14:18:12 +02:00
|
|
|
[source,text]
|
2021-06-08 14:23:48 +02:00
|
|
|
----
|
|
|
|
try {
|
|
|
|
/* ... */
|
|
|
|
} catch (MyException e) { // Compliant - something is done before throwing again the exception
|
|
|
|
fixSomething();
|
|
|
|
throw e;
|
|
|
|
}
|
|
|
|
----
|
|
|
|
|
|
|
|
|