Kotlin

Kotlin

Made by DeepSource

Ensure exceptions that are caught are actually handled KT-W1005

Anti-pattern
Major

Avoid "swallowing" exceptions by catching them and leaving the exception variable unused.

Exceptions should not be swallowed. This rule reports all instances where exceptions are caught and not correctly passed (e.g. as a cause) into a newly thrown exception.

If your repository contains a Detekt configuration file, this issue will respect any configuration for the SwallowedException Detekt rule.

By default, this issue will not report exception types that are usually ignored, specifically the following ones:

  • InterruptedException
  • MalformedURLException
  • NumberFormatException
  • ParseException

Bad Practice

fun foo() {
    try {
        // ...
    } catch(e: IOException) {
        throw MyException(e.message) // e is swallowed
    }
    try {
        // ...
    } catch(e: IOException) {
        throw MyException() // e is swallowed
    }
    try {
        // ...
    } catch(e: IOException) {
        bar() // exception is unused
    }
}

Recommended

Pass the exception as the cause to another, more specific exception.

fun foo() {
    try {
        // ...
    } catch(e: IOException) {
        throw MyException(e)
    }