Kotlin - Throw Custom Exception

Viewed 63417

How can I throw a custom exception in Kotlin? I didn't really get that much off the docs...

In the docs, it gets described what each exception needs, but how exactly do I implement it?

5 Answers

Most of these answers just ignore the fact that Exception has 4 constructors. If you want to be able to use it in all cases where a normal exception works do:

class CustomException : Exception {
    constructor() : super()
    constructor(message: String) : super(message)
    constructor(message: String, cause: Throwable) : super(message, cause)
    constructor(cause: Throwable) : super(cause)
}

this overwrites all 4 constructors and just passes the arguments along.

EDIT: Please scroll down to R. Agnese answer, it manages to do this without overriding 4 constructors which is error prone.

I know this is old, but I would like to elaborate on @DownloadPizza's answer: https://stackoverflow.com/a/64818325/9699180

You don't actually need four constructors. You only need two to match the base Exception class's four:

class CustomException(message: String? = null, cause: Throwable? = null) : Exception(message, cause) {
    constructor(cause: Throwable) : this(null, cause)
}

The Exception base class comes from the Java standard library, and Java doesn't have default parameters, so the Java class must have four constructors for every combination of acceptable inputs. Furthermore, both message and cause are allowed to be null in Exception, so ours should be, too, if we're trying to be 100% compatible with Exception.

The only reason we even need the second constructor is to avoid needing to use named argument syntax in Kotlin code: CustomException(cause = fooThrowable) vs Exception(fooThrowable).

Why not merge both answers

Suppose you want to throw a custom Exception in the Calculator. Logging is optional you can remove the init block

class CalculationException constructor(message: String= "ERROR: Invalid Input", cause: Throwable): Exception(message, cause) {
    init {
        Log.e("CalculationException", message, cause)
    }
}

Usage:

No Message

    throw(CalculationException())

Output: Default Message

Caused by: CalculationException: ERROR: Invalid Input


OR

Only message no cause

    throw(CalculationException("Some Weird Exception"))
enter code here

Output: Custom Message

Process: PID: 23345 java.lang.RuntimeException: Unable to start activity ComponentInfo{CalculationException: Some Weird Exception


OR

Both message and Cause

    throw(CalculationException("Divide ByZero", ArithmeticException()))

2021-08-12 19:36:55.705 17411-17411/ E/CalculationException: Divide ByZero java.lang.ArithmeticException

Related