Govur University Logo
--> --> --> -->
...

How does Kotlin handle exception handling and error management? Explain with code examples.



In Kotlin, exception handling and error management are achieved through a combination of try-catch blocks and the use of the `throw` keyword. Kotlin's exception handling mechanism is similar to other programming languages and provides a structured way to handle and propagate errors. Let's explore how exception handling works in Kotlin with code examples.

1. Handling Exceptions with try-catch:
To handle exceptions in Kotlin, you can enclose the code that might throw an exception within a `try` block, followed by one or more `catch` blocks that handle specific exceptions. If an exception occurs within the `try` block, the corresponding `catch` block is executed to handle the exception.

Example:

```
kotlin`fun divide(a: Int, b: Int): Int {
return try {
a / b
} catch (e: ArithmeticException) {
println("Division by zero error!")
-1
}
}

// Usage
val result = divide(10, 0)
if (result != -1) {
println("Result: $result")
}`
```
In the example above, the `divide` function attempts to perform division. If a `DivideByZeroException` occurs, the catch block is executed, and an error message is printed. The function returns `-1` as an indication of an error. The result of the division is checked outside the function, and if it's not equal to `-1`, the result is printed.

2. Propagating Exceptions:
In Kotlin, exceptions can also be propagated to the calling code by using the `throw` keyword. This allows higher-level code to handle or propagate the exception further.

Example:

```
kotlin`fun calculatePercentage(marks: Int, total: Int): Double {
if (total == 0) {
throw IllegalArgumentException("Total marks cannot be zero.")
}
return (marks.toDouble() / total) * 100
}

// Usage
try {
val percentage = calculatePercentage(85, 0)
println("Percentage: $percentage")
} catch (e: IllegalArgumentException) {
println("Error: ${e.message}")
}`
```
In the example above, the `calculatePercentage` function throws an `IllegalArgumentException` if the `total` parameter is zero. This exception is propagated to the calling code, where it is caught and an appropriate error message is printed.

3. Finally Block:
Kotlin provides the `finally` block, which is executed regardless of whether an exception occurs or not. This block is used to perform cleanup operations or release resources.

Example:

```
kotlin`fun readFile() {
val file = File("example.txt")
try {
val content = file.readText()
println(content)
} catch (e: FileNotFoundException) {
println("File not found!")
} finally {
file.close()
}
}`
```
In the example above, the `finally` block ensures that the file is closed even if an exception occurs while reading the file.

Kotlin also supports creating custom exceptions by extending the `Exception` class or any of its subclasses. This allows you to define your own exception types to handle specific scenarios in your code.

Overall, Kotlin provides a robust exception handling mechanism with try-catch blocks, exception propagation, and the ability to define custom exceptions. By effectively handling exceptions and errors, you can ensure that your code gracefully handles unexpected situations and provides meaningful feedback to users.