Kotlin

Kotlin

Made by DeepSource

Method should not throw exceptions KT-W1056

Bug risk
Major

Avoid throwing exceptions in non-fallible operations such as equals() or toString().

This issue is reported on functions which should never throw an exception. By default, the Kotlin analyzer checks for toString, hashCode, equals and finalize.

If your repository contains a Detekt configuration file, this issue will respect any configuration you have created for the ExceptionRaisedInUnexpectedLocation rule.

Bad Practice

class Foo {
    override fun toString(): String {
        throw IllegalStateException() // exception should not be thrown here
    }
}

Recommended

Instead of throwing an exception, handle the failure condition in a different way. For example, you can return a default value or indicate failure using a special value or error code.

class Foo {
    override fun toString(): String {
        if (badState())
            return ""
    }
}

This will improve the reliability and predictability of the code.

References: - Detekt - ExceptionRaisedInUnexpectedLocation