🚨 Kotlin Exception Handling – try, catch, finally, throw & Custom Errors
🧲 Introduction – Handle Errors Gracefully with Kotlin Exception Handling
In real-world applications, errors and unexpected conditions are inevitable. Kotlin provides a robust and expressive exception handling system that lets you gracefully manage runtime problems such as invalid input, failed network calls, or null values.
With constructs like try
, catch
, finally
, and throw
, Kotlin’s error handling is clean and developer-friendly. You can also define custom exceptions to handle domain-specific logic effectively.
🎯 In this guide, you’ll learn:
- How to handle runtime exceptions using
try-catch-finally
- How and when to use
throw
andthrows
- How to create and use custom exceptions in Kotlin
- Best practices for safe, clean error management
📘 Topics Covered
🧱 Topic | 📖 Description |
---|---|
🛠️ Kotlin – Exception Handling | Using try , catch , and finally blocks to handle exceptions. |
🚫 Kotlin – Throw & Throws | Manually throwing exceptions and declaring throwable functions. |
✍️ Kotlin – Custom Exceptions | Creating user-defined exception classes for app-specific error scenarios. |
🔍 Detailed Sections & Examples
🛠️ Kotlin – Exception Handling (try-catch-finally)
fun divide(a: Int, b: Int): Int {
return try {
a / b
} catch (e: ArithmeticException) {
println("Error: ${e.message}")
0
} finally {
println("Execution completed.")
}
}
🧠 Explanation:
try
block wraps risky code.catch
handles specific exceptions.finally
executes always (for cleanup or logging).
✅ Output Example:
Error: / by zero
Execution completed.
🚫 Kotlin – Throw & Throws
fun validateAge(age: Int) {
if (age < 18) {
throw IllegalArgumentException("Age must be 18 or above")
}
}
📌 throw
is used to explicitly throw an exception.
💡 Unlike Java, Kotlin doesn’t require throws
declarations—but it supports interoperability with Java’s @Throws
annotation:
@Throws(IOException::class)
fun readFile() {
// might throw IOException
}
✍️ Kotlin – Custom Exceptions
class InvalidInputException(message: String) : Exception(message)
fun process(input: String) {
if (input.isEmpty()) throw InvalidInputException("Input cannot be empty")
}
try {
process("")
} catch (e: InvalidInputException) {
println("Custom Exception: ${e.message}")
}
✅ Custom exceptions let you create meaningful, domain-specific error classes for better readability and structure.
📌 Summary – Recap & Next Steps
Exception handling in Kotlin allows developers to write safe, crash-resistant code using clean and expressive syntax. From built-in handling to custom exceptions, Kotlin gives you powerful tools to catch, log, and respond to problems in real time.
🔍 Key Takeaways:
- Use
try-catch-finally
to handle and recover from runtime errors. - Throw exceptions manually with
throw
for validation and control flow. - Define custom exception classes to represent specific failure conditions.
- Kotlin doesn’t enforce
throws
but supports it for Java interop.
⚙️ Practical Use Cases:
- Handling null pointer and arithmetic errors
- Validating user input and throwing exceptions
- Building clean error interfaces for APIs or services
❓ Frequently Asked Questions
❓ Is finally
always executed in Kotlin?
✅ Yes. The finally
block runs regardless of exception—ideal for resource cleanup.
❓ What’s the Kotlin equivalent of Java’s throws
keyword?
✅ Kotlin doesn’t require checked exceptions but supports @Throws
for Java interop.
❓ Can I throw multiple exception types in Kotlin?
✅ Yes. Use multiple catch
blocks:
try {
// risky code
} catch (e: IOException) {
} catch (e: NullPointerException) {
}
❓ Are all exceptions in Kotlin unchecked?
✅ Yes. Kotlin treats all exceptions like unchecked—no compile-time enforcement of try/catch
.
❓ When should I create a custom exception?
✅ When you need to represent a specific business rule or domain error in your application logic.
Share Now :