Challenge - 5 Problems
Try-Catch Expression Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of try-catch expression with successful try block
What is the output of this Kotlin code snippet?
Kotlin
val result = try { val x = 10 / 2 "Success: $x" } catch (e: ArithmeticException) { "Error" } println(result)
Attempts:
2 left
💡 Hint
Remember that try-catch in Kotlin can return a value from the try block if no exception occurs.
✗ Incorrect
The try block executes successfully without exceptions, so the expression returns "Success: 5".
❓ Predict Output
intermediate2:00remaining
Output when exception is thrown in try block
What will be printed by this Kotlin code?
Kotlin
val result = try { val x = 10 / 0 "Success: $x" } catch (e: ArithmeticException) { "Error caught" } println(result)
Attempts:
2 left
💡 Hint
Division by zero throws an exception, so the catch block runs.
✗ Incorrect
The division by zero causes an ArithmeticException, so the catch block returns "Error caught".
❓ Predict Output
advanced2:00remaining
Value of variable after try-catch expression with finally
What is the value of variable 'result' after running this Kotlin code?
Kotlin
val result = try { "Try block" } catch (e: Exception) { "Catch block" } finally { println("Finally block executed") } println(result)
Attempts:
2 left
💡 Hint
Finally block runs but does not affect the returned value.
✗ Incorrect
The try block returns "Try block". The finally block runs but does not change the result.
❓ Predict Output
advanced2:00remaining
Output when catch block throws exception in try-catch expression
What happens when this Kotlin code runs?
Kotlin
val result = try { val x = 10 / 0 "Success" } catch (e: ArithmeticException) { throw IllegalStateException("New exception") } println(result)
Attempts:
2 left
💡 Hint
The catch block throws a new exception instead of returning a value.
✗ Incorrect
The try block throws ArithmeticException, caught by catch, which then throws IllegalStateException. No value is returned.
🧠 Conceptual
expert2:00remaining
Why is try-catch an expression in Kotlin?
Which statement best explains why try-catch is an expression in Kotlin?
Attempts:
2 left
💡 Hint
Think about how try-catch can be used in assignments.
✗ Incorrect
In Kotlin, try-catch is an expression that returns a value from either the try or catch block, enabling concise error handling and assignment.