Kotlin Custom Exception Tutorial

In this section, we will learn what the custom exception is and how to create on in Kotlin.

What is user defined exception in Kotlin? (Kotlin custom exception)

In Kotlin, there are lots of built-in exception types (classes) and each is here for a specific purpose!

For example, if you try to access the members of a variable that has a null value, you’ll get an exception of type NullPointerException class! It’s the purpose of this class to be used for creating exception objects when a program tries to call a null value and access its members!

Another exception class is called ArrayIndexOutOfBoundException and it is automatically used to create exception objects when our program tries to access an index number of an array that is out of its range! For example, if an array has 10 elements only and we call for the element number 30, then we will get an exception of this type.

But then there are times that none of the mentioned exception classes could server the purpose of a specific exception! For example, let’s say we have a database connection and want to alert users by throwing an exception and explain that the connection is lost so that they should do something to reconnect the program to the database! Here you don’t have an exception class specifically for this purpose (Of course you can simply use the Exception class which is a general one and use that for throwing a new exception but that’s not a specifically designed exception class for such purpose.)!

Now in Kotlin, we can create our own exception class simply by creating a class with any name and make that to inherit from the Throwable class (or one of the built-in exception classes if our new exception type relates to them!).

This way we can use this custom exception and create our exception object with a custom type!

How to create user defined exception in Kotlin?

As mentioned before, simply make a class to inherit from the Throwable class and that class becomes an exception type class.

Example: creating custom exception in Kotlin

class CustomException(message:String):Throwable(message){


fun main(){
        throw CustomException("This is an exception created from a custom exception class")


This is an exception created from a custom exception class

Kotlin Custom Exception Note:

When creating a custom exception, it’s important to set a parameter of type string and then pass this parameter as the argument of the Throwable class constructor or any other built-in exception type that we’ve used as the parent of our custom exception class.

This way we can call properties like message in order to access the value (reason) of the thrown exception in the body of the catch handlers.


Top Technologies