Create 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.

In addition to the built-in Exception Classes, you can create your own type of Exception that reflects your own cause of 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.

Each Exception has following three properties :

  • Message
  • Stack Trace
  • Cause (Optional)

We shall learn how to use these properties with a custom exception.

Syntax – Kotlin Custom Exception

The create custom Exception class should extend Exception class. Following is the syntax of Custom Exception in Kotlin

</>
Copy
class CustomExceptionName(message: String) : Exception(message)

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.

custon_exception.kt

</>
Copy
class InvalidNameException(message: String) : Exception(message)

example.kt

</>
Copy
fun main(args: Array<String>) {

    var name = "Tutorial 60"

    try {
        validateName(name)
    } catch (e : InvalidNameException){
        println(e.message)
    } catch (e : Exception){
        println(e.message)
    }

}

fun validateName(name : String){
    if(name.matches(Regex(".*\\d+.*"))) {
        throw InvalidNameException("Your name : $name : contains numerals.")
    }
}

Output

Your name : Tutorial 60 : contains numerals.

Example 2 – Multiple Custom Exceptions

In this Example, we shall create two custom exceptions.

A koltin file can contain any number of classes. And so is our CustomExceptions.kt class. In this example, it contains two custom Exception classes.

custom_exception.kt

</>
Copy
class InvalidNameException(message: String) : Exception(message)

class InvalidAgeException(message: String) : Exception(message)

example.kt

</>
Copy
fun main(args: Array<String>) {

    var name = "Tutorial 60"
    var age = 2

    try {
        validateName(name)
    } catch (e : InvalidNameException){
        println(e.message)
    } catch (e : InvalidAgeException){
        println(e.message)
    }

    try {
        validateAge(age)
    } catch (e : InvalidNameException){
        println(e.message)
    } catch (e : InvalidAgeException){
        println(e.message)
    }

}

fun validateName(name : String){
    if(name.matches(Regex(".*\\d+.*"))) {
        throw InvalidNameException("Your name : $name : contains numerals.")
    }
}

fun validateAge(age : Int){
    if(age <18 || age > 100) {
        throw InvalidNameException("Your age $age did not meet the criteria.")
    }
}

Output

Your name : Tutorial 60 : contains numerals.
Your age 2 did not meet the criteria.

Conclusion

In this Kotlin TutorialKotlin Custom Exception, we have learnt how to define a custom exception and throw it to the calling method.