Kotlin – Custom Exception

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 – To Create Kotlin Custom Exception

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

class CustomExceptionName(message: String) : Exception(message)

Example – 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.

Example – 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.

Conclusion

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