ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

Exception Handling in Kotlin

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='25' AND `tutorial_submenu`='102' AND `tutorial_status`=1 LIMIT 1

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:

kotlin

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:

kotlin

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:

kotlin

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:

kotlin

fun (age: Int) { fun () { try { validateAge(16) } catch (e: IllegalArgumentException) { println("Exception: ${e.message}") }}

Output:

makefile

class InvalidUserException(message: String) : Exception(message)fun (username: String) { fun () { try { login("user123") } catch (e: InvalidUserException) { println("Exception: ${e.message}") }}

Output:

makefile

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.

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql