/**
* Kotlin Lab 1: Introduction to Exception Handling
*
* This lab introduces basic exception handling in Kotlin using try-catch blocks,
* demonstrates handling different exception types, and shows how to access
* exception information.
*/
fun main() {
println("=== Kotlin Exception Handling: Introduction ===\n")
// Basic try-catch
println("1. Basic try-catch:")
try {
val result = 10 / 0
println("This won't be printed because an exception is thrown")
} catch (e: Exception) {
println("Caught an exception: ${e.message}")
println("Exception type: ${e.javaClass.simpleName}\n")
}
// Handling specific exception types
println("2. Handling specific exception types:")
try {
val numbers = listOf(1, 2, 3)
println(numbers[5]) // This will throw IndexOutOfBoundsException
} catch (e: IndexOutOfBoundsException) {
println("Caught IndexOutOfBoundsException: ${e.message}")
} catch (e: Exception) {
println("Caught some other exception: ${e.message}\n")
}
// Using try as an expression
println("3. Using try as an expression:")
val result = try {
val number = "abc".toInt()
"Result: $number" // This won't be assigned to result
} catch (e: NumberFormatException) {
"Conversion failed: ${e.message}" // This will be assigned to result
}
println("$result\n")
// Accessing exception details
println("4. Accessing exception details:")
try {
throw RuntimeException("Something went wrong", IllegalArgumentException("Invalid input"))
} catch (e: RuntimeException) {
println("Message: ${e.message}")
println("Cause: ${e.cause?.javaClass?.simpleName}")
// Print stack trace
println("Stack trace:")
e.stackTrace.take(3).forEach { element ->
println(" at ${element.className}.${element.methodName}(${element.fileName}:${element.lineNumber})")
}
println()
}
// Uncaught exceptions
println("5. Uncaught exceptions:")
handlePotentialProblem()
println("Program completed successfully!")
}
fun handlePotentialProblem() {
try {
riskyOperation()
println("Risky operation completed successfully")
} catch (e: Exception) {
println("Handled an exception from riskyOperation(): ${e.message}\n")
}
}
fun riskyOperation() {
val data = mapOf("a" to 1, "b" to 2)
val value = data["c"] ?: throw NoSuchElementException("Key 'c' not found in the map")
println("Value: $value") // This won't be executed
}