Kotlin - Throw Custom Exception

ExceptionKotlin

Exception Problem Overview


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?

Exception Solutions


Solution 1 - Exception

One thing to keep in mind: if you are using the IntelliJ IDE, just a simple copy/paste of Java code can convert it to Kotlin.

Coming to your question, now. If you want to create a custom Exception, just extend Exception class like:

class TestException(message:String): Exception(message)

and throw it like:

throw TestException("Hey, I am testing it")

Solution 2 - Exception

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.

Solution 3 - Exception

Like this:

Implementation

class CustomException(message: String) : Exception(message)

Usage

 fun main(args: Array<String>) {
     throw CustomException("Error!")            // >>> Exception in thread "main"
 }                                              // >>> CustomException: Error!

For more info: Exceptions

Solution 4 - Exception

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).

Solution 5 - Exception

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOhMadView Question on Stackoverflow
Solution 1 - Exceptionchandil03View Answer on Stackoverflow
Solution 2 - ExceptionDownloadPizzaView Answer on Stackoverflow
Solution 3 - ExceptionAlexander RomanovView Answer on Stackoverflow
Solution 4 - ExceptionR. AgneseView Answer on Stackoverflow
Solution 5 - ExceptionHitesh SahuView Answer on Stackoverflow