Kotlin - Throw Custom Exception

Solution 1:

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:

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:

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