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?
Example 1 – Create Custom Exception in Kotlin In this Example, we shall create a custom exception named InvalidNameException, which we shall throw when name of a person is invalid. fun main(args: Array<String>) { var name = "Tutorial 60" try { validateName(name) } catch (e : InvalidNameException){ println(e.
Kotlin does not support throwing multiple exceptions at the same time, however we can implement this functionality using some other functions provided by the Kotlin library.
In Kotlin, we use try-catch block for exception handling in the program. The try block encloses the code which is responsible for throwing an exception and the catch block is used for handling the exception. This block must be written within the main or other methods.
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")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With