![]() |
VOOZH | about |
In addition to the built-in Exception Classes, you can create your own type of Exception that reflects your own cause of the exception. And you will appreciate the use of Custom Exception when you have multiple catch blocks for your try expression and can differentiate the custom exception from regular ones. Sometimes, there are cases where you want to create your own exception. If you are creating your own exception, it's known as a custom exception or user-defined exception. These are used to customize the exception according to a specific need, and using this, you can have your own exception and a message. In this article, we will see how to create and throw a custom exception in Kotlin.
Kotlin provides many built-in Exception Classes like IOException, ClassNotFoundException, ArithmeticException, etc. These are thrown at runtime by JVM when it encounters something it could not handle.
class CustomException (message: String) : Exception(message)
Now, if you have to throw an Exception, you will need to simply do the following:
throw CustomException ("threw custom exception")
The output will be something like this:
👁 ImageLet's take a look at the implementation of the Exception class:
As you can see,
Note: If you are using the IntelliJ IDE, just a simple copy/paste of Java code can convert it to Kotlin.