Create Custom Exception In Kotlin Tutorial With Example

In this kotlin tutorial, we will learn about how to create custom exception in kotlin? we will see why do we need to use kotlin custom exception etc. Then, we will see different examples on custom exception. At last, we will see different exercises on custom exception in kotlin.

As we already know, Exception handling is a way to stop the program from being terminated abruptly when certain situation arises.

In kotlin, we already have some built-in exceptions. For example, IOException, ArithmeticException, ClassNotFoundException etc.

Each exception has some basic properties in common –

A. Message
B. Stack Trace
C. Cause – This is optional.

So, while creating any custom exception in kotlin, you must take care of these common things.

Syntax to Create Custom Exception in Kotlin

class MyExceptionClassName(message: String) : Exception(message)

Using this syntax, you can create any custom exception in kotlin program.

Example of Kotlin Custom Exception

Here, we are creating an exception class NameNotValidException that is thrown when a name is not valid.

fun main(args: Array<String>) {
    val name = "Tutorialwing 60"
    try {
        validateName(name)
    } catch (e: NameNotValidException) {
        println(e.message)
    } catch (e: Exception) {
        println(e.message)
    }
}

fun validateName(name: String) {
    if (name.matches(Regex(".*\\d+.*"))) {
        throw NameNotValidException("Your name '$name' contains numeric letters.")
    }
}

class NameNotValidException(message: String) : Exception(message)

When you run the above program, you will get below output –
Your name ‘Tutorialwing 60’ contains numeric letters.

Notice that NameNotValidException is thrown because name is ‘Tutorialwing 60’ that contains number in it.

Sometimes we need to create multiple exceptions in kotlin program. We can do so as described below –

Example to Create Kotlin Multiple Custom Exception

You can create multiple exceptions in kotlin in the same way as you create a custom exception.

Let’s take an example to understand it clearly

fun main(args: Array<String>) {
    val name = "Tutorialwing"
    val age = 5;
    try {
        validateName(name)
        try {
            validateAge(age)
        } catch (e: AgeNotValidException) {
            println(e.message)
        }
    } catch (e: NameNotValidException) {
        println(e.message)
    } catch (e: Exception) {
        println(e.message)
    }
}

fun validateAge(age: Int) {
    if (age < 18 || age > 100) {
        throw AgeNotValidException("Age must be between 18 and 100 years")
    }
}

fun validateName(name: String) {
    if (name.matches(Regex(".*\\d+.*"))) {
        throw NameNotValidException("Your name '$name' contains numeric letters.")
    }
}

class NameNotValidException(message: String) : Exception(message)

class AgeNotValidException(message: String) : Exception(message)

When you run the program, you will get output as below –
Age must be between 18 and 100 years

Here, we have defined two custom exceptions in kotlin. They are – NameNotValidException and AgeNotValidException.
Similarly, you can define you custom exception as per your need.

Exercises on Kotlin Custom Exceptions

1. Guess the output of below program

fun main(args: Array<String>) {
    val name = "Tutoria1wing "
    val age = 5;
    try {
        validateName(name)
        try {
            validateAge(age)
        } catch (e: AgeNotValidException) {
            println(e.message)
        }
    } catch (e: NameNotValidException) {
        println(e.message)
    } catch (e: Exception) {
        println(e.message)
    }
}

fun validateAge(age: Int) {
    if (age < 18 || age > 100) {
        throw AgeNotValidException("Age must be between 18 and 100 years")
    }
}

fun validateName(name: String) {
    if (name.matches(Regex(".*\\d+.*"))) {
        throw NameNotValidException("Your name '$name' contains numeric letters.")
    }
}

class NameNotValidException(message: String) : Exception(message)

class AgeNotValidException(message: String) : Exception(message)

Output –
Your name ‘Tutoria1wing’ contains numeric letters.

Notice that name is being initialized with ‘Tutoria1wing’ not ‘Tutorialwing’. ‘Tutoria1wing’ contains number ‘1’ in it.

Leave a Reply