0
0
Kotlinprogramming~5 mins

Custom exception classes in Kotlin

Choose your learning style9 modes available
Introduction

Custom exception classes help you create your own error types. This makes your program clearer and easier to fix when something goes wrong.

When you want to show a specific error message for a special problem in your program.
When you want to catch and handle different errors in different ways.
When you want to make your code easier to understand by naming errors clearly.
When you want to add extra information to an error to help debugging.
When you want to separate your program's errors from system or library errors.
Syntax
Kotlin
class MyCustomException(message: String) : Exception(message)
Use class keyword to create a new exception class.
Your class should extend Exception or another exception type.
Examples
A simple custom exception for invalid age errors.
Kotlin
class InvalidAgeException(message: String) : Exception(message)
Custom exception to indicate wrong file format.
Kotlin
class FileFormatException(message: String) : Exception(message)
Exception for network-related errors.
Kotlin
class NetworkErrorException(message: String) : Exception(message)
Sample Program

This program defines a custom exception InvalidAgeException. The checkAge function throws this exception if the age is not realistic. The main function tries to check an invalid age and catches the custom exception to print a friendly message.

Kotlin
fun checkAge(age: Int) {
    if (age < 0 || age > 150) {
        throw InvalidAgeException("Age $age is not valid.")
    } else {
        println("Age $age is valid.")
    }
}

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

fun main() {
    try {
        checkAge(200)
    } catch (e: InvalidAgeException) {
        println("Caught an error: ${e.message}")
    }
}
OutputSuccess
Important Notes

Always give your custom exceptions clear and meaningful names.

You can add more properties or functions to your custom exception if needed.

Use throw to raise your custom exception when a problem happens.

Summary

Custom exceptions let you create your own error types with clear names.

They help make your code easier to read and debug.

Use class MyException : Exception() to define them.