Kotlin Exception Handling Tutorial: try, catch, finally, and Custom Exceptions


This Kotlin Exception Handling tutorial explains how to handle runtime errors safely using try, catch, and finally blocks, and how to create and use custom exceptions. With clear examples and best practices, this chapter helps developers build robust and fault-tolerant Kotlin applications.

Kotlin Exception Handling – Complete Tutorial

What Is Exception Handling?

Exception handling allows a program to handle runtime errors gracefully without crashing the application.

try, catch, finally

Basic Syntax


try {
// risky code
} catch (e: Exception) {
// handle exception
} finally {
// always executes
}

Example: Handling Arithmetic Exception


fun main() {
try {
val result = 10 / 0
println(result)
} catch (e: ArithmeticException) {
println("Cannot divide by zero")
} finally {
println("Execution completed")
}
}

Multiple catch Blocks


try {
val number = "abc".toInt()
} catch (e: NumberFormatException) {
println("Invalid number format")
} catch (e: Exception) {
println("General exception")
}

Best Practices

  1. Catch specific exceptions first.
  2. Avoid catching generic Exception unless necessary.
  3. Use finally for resource cleanup.

try as an Expression

In Kotlin, try can return a value.


fun main() {
val result = try {
"123".toInt()
} catch (e: NumberFormatException) {
0
}
println(result)
}

Custom Exceptions

Custom exceptions allow defining application-specific error conditions.

Creating a Custom Exception


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

Throwing a Custom Exception


fun validateAge(age: Int) {
if (age < 18) {
throw InvalidAgeException("Age must be 18 or above")
}
}

Using Custom Exception


fun main() {
try {
validateAge(15)
} catch (e: InvalidAgeException) {
println(e.message)
}
}

Best Practices for Custom Exceptions

  1. Extend Exception or a specific subclass.
  2. Provide meaningful error messages.
  3. Use custom exceptions for business logic errors.

Checked vs Unchecked Exceptions

  1. Kotlin does not have checked exceptions.
  2. All exceptions are unchecked and handled at runtime.

Best Practice

  1. Document exceptions clearly in function documentation.

Summary

This chapter explained Kotlin exception handling using try, catch, and finally, including handling multiple exceptions and using try as an expression. It also covered creating and using custom exceptions for application-specific error handling. Proper exception handling improves application reliability and maintainability.