Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 25 / 68

Writing a Custom Exception Class

In this lesson you will learn how to define your own exception class in Kotlin so you can describe error conditions more precisely. This is for anyone searching for "Kotlin custom exception how to create".

Inheriting from Exception gives you an exception of your own. Naming a class per kind of failure makes it much easier to tell what went wrong when you catch it.

The sample code defines a custom exception in the single line class ValidationError(message: String) : Exception(message) and throws it inside checkAge() when the age is negative. The concision of Kotlin class definitions pays off here too.

A common stumbling block for beginners is sticking with the built-in Exception and losing the ability to tell error types apart. Once you can distinguish "invalid input" from "network failure", you can write a response suited to each.

In real-world development, the larger the application, the more this kind of error-type design matters.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)