Throwing Same Exception
ID |
kotlin.throwing_same_exception |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Kotlin |
Tags |
catch, exception, stack-trace |
Description
Reports catch (e: X) { … throw X(…) … } patterns where the catch body constructs and
throws a brand-new instance of the same declared exception type without passing the caught
exception e as a cause. The original cause and stack trace are lost.
Rationale
// Bad — cause discarded
try { ... } catch (e: IOException) {
throw IOException("retrying failed") // FLAW
}
// OK — original cause is preserved
try { ... } catch (e: IOException) {
throw IOException("retrying failed", e)
}
// OK — different exception type
try { ... } catch (e: IOException) {
throw IllegalStateException("wrapped", e)
}
// OK — bare rethrow (handled by kotlin.rethrow_caught_exception)
try { ... } catch (e: IOException) {
throw e
}
A new exception of the same type effectively re-throws but drops the inner stack trace, so the diagnostic value of the catch is negative.
Remediation
-
Pass the caught exception as the cause argument:
throw X("msg", e). -
Use a bare rethrow when no additional context is needed:
throw e. -
If the catch performs work and then rethrows, log the original exception with the catch parameter rather than constructing a new instance.