How to Create Custom Exception in Kotlin: Simple Guide
In Kotlin, you create a custom exception by defining a class that extends
Exception or any of its subclasses. You can add a constructor to pass a message or cause, then throw your custom exception using throw.Syntax
To create a custom exception, define a class that inherits from Exception. You can add a primary constructor to accept an error message or cause.
- class: declares the class
- CustomException: your exception name
- : Exception(message): inherits from
Exceptionand passes the message
kotlin
class CustomException(message: String) : Exception(message)Example
This example shows how to define a custom exception and throw it when a condition is met. The try-catch block catches the exception and prints its message.
kotlin
class MyCustomException(message: String) : Exception(message) fun checkNumber(num: Int) { if (num < 0) { throw MyCustomException("Negative numbers are not allowed: $num") } else { println("Number is $num") } } fun main() { try { checkNumber(-5) } catch (e: MyCustomException) { println("Caught exception: ${e.message}") } }
Output
Caught exception: Negative numbers are not allowed: -5
Common Pitfalls
Common mistakes include not extending Exception or forgetting to pass the message to the superclass. Also, throwing exceptions without meaningful messages makes debugging harder.
Wrong way: defining a class without extending Exception will not behave as an exception.
kotlin
class WrongException(message: String) { // This is NOT an exception because it does not extend Exception } // Correct way: class RightException(message: String) : Exception(message)
Quick Reference
- Define custom exception by extending
ExceptionorRuntimeException. - Use
throwto raise the exception. - Catch with
try-catchblocks. - Always provide meaningful messages for clarity.
Key Takeaways
Create custom exceptions by extending the Exception class in Kotlin.
Pass error messages to the superclass constructor for clarity.
Throw your custom exception using the throw keyword.
Catch exceptions with try-catch blocks to handle errors gracefully.
Avoid defining exception classes without extending Exception.