
Exception Handling in Kotlin
📌 Exception Handling in Kotlin
Exception Handling in Kotlin is a mechanism to handle runtime errors, preventing the application from crashing. It allows you to manage and respond to unexpected issues effectively.
✅ 1. What is an Exception?
An exception is an unwanted or unexpected event that occurs during program execution, disrupting the normal flow. Examples include:
Division by zero
Accessing an invalid index in an array
Null pointer references
✅ 2. Try-Catch Block
Kotlin uses try-catch
blocks to catch and handle exceptions.
📌 Syntax:
fun () { try { val result = 10 / 0 println(result) } catch (e: ArithmeticException) { println("Exception caught: ${e.message}") } Exception caught: / by zeroExecution completed.
✅ 3. Multiple Catch Blocks
You can use multiple catch
blocks to handle different types of exceptions.
📌 Example:
fun () { val str: String? = null try { println(str!!.length) // Throws NullPointerException } catch (e: NullPointerException) { println("Null Pointer Exception: ${e.message}") } Null Pointer Exception: null
Kotlin executes the appropriate
catch
block based on the exception.
✅ 4. Finally Block
The finally
block always executes, whether an exception occurs or not. It is typically used for cleanup operations like closing files or releasing resources.
📌 Example:
fun () { try { val data = arrayOf(1, 2, 3) println(data[5]) // ArrayIndexOutOfBoundsException } catch (e: Exception) { println("Exception: ${e.message}") } Exception: Index 5 out of bounds for length 3This will always execute.
✅ 5. Throwing Exceptions
You can throw exceptions using the throw
keyword.
📌 Example:
fun (age: Int) { fun () { try { validateAge(16) } catch (e: IllegalArgumentException) { println("Exception: ${e.message}") }}
Output:
class InvalidUserException(message: String) : Exception(message)fun (username: String) { fun () { try { login("user123") } catch (e: InvalidUserException) { println("Exception: ${e.message}") }}
Output:
Exception: Invalid username: user123
✅ 7. Conclusion
Use
try-catch-finally
to handle exceptions.Handle specific exceptions using multiple
catch
blocks.Use the
finally
block for cleanup operations.Throw exceptions using
throw
.Create custom exceptions by extending the
Exception
class.