Kotlin - Throw Custom 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)
.
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.
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")