Look at this Kotlin code. What will it print?
fun main() { val numbers = listOf(1, 2, 0, 4) for (num in numbers) { try { val result = 10 / num println("Result: $result") } catch (e: ArithmeticException) { println("Cannot divide by zero") } } }
Think about what happens when dividing by zero inside the try block.
The code tries to divide 10 by each number. When it reaches zero, it throws an ArithmeticException, which is caught and prints "Cannot divide by zero". Other divisions print the result.
Why is it important for programs to handle errors properly?
Think about user experience and program stability.
Handling errors prevents crashes and helps users understand what went wrong, improving reliability and user trust.
Find the mistake in this Kotlin code that tries to handle exceptions.
fun main() { try { val text = "abc" val number = text.toInt() println(number) } catch (e: NumberFormatException) { println("Conversion failed") } catch (e: Exception) { println("General error") } catch (e: Throwable) { println("Unknown error") } }
Think about the order of catch blocks from specific to general exceptions.
In Kotlin, catch blocks must be ordered from most specific to most general. Throwable is the base class and should be last. Otherwise, the compiler will error.
What error will this Kotlin code cause?
fun main() { try { val list = listOf(1, 2, 3) println(list[5]) } catch (e: IndexOutOfBoundsException) { println("Index error caught") } catch (e: Exception) { println("Other error") } }
What happens when you access an invalid list index?
Accessing list[5] throws IndexOutOfBoundsException, which is caught and prints "Index error caught".
Consider this Kotlin function that handles errors. What will be the value of result after calling safeDivide(10, 0)?
fun safeDivide(a: Int, b: Int): Int { return try { a / b } catch (e: ArithmeticException) { -1 } finally { println("Operation attempted") } } fun main() { val result = safeDivide(10, 0) println("Result is $result") }
Remember what the catch block returns and how finally works.
The division by zero throws ArithmeticException, caught and returns -1. The finally block runs but does not change the return value.