Recall & Review
beginner
What does it mean that try-catch is an expression in Kotlin?
In Kotlin, try-catch can return a value, so you can assign the result of a try-catch block to a variable. This means try-catch is an expression, not just a statement.
Click to reveal answer
beginner
How do you assign a value from a try-catch block to a variable?
You write: val result = try { /* code */ } catch (e: Exception) { /* fallback value */ }
Click to reveal answer
beginner
What happens if an exception is thrown inside the try block when used as an expression?
The catch block runs and its value is returned as the result of the try-catch expression.
Click to reveal answer
intermediate
Can the try block and catch block return different types when used as an expression?
No, both blocks must return compatible types so the expression has a consistent type.
Click to reveal answer
beginner
Why is using try-catch as an expression useful?
It lets you write concise code by handling exceptions and returning fallback values in one expression, avoiding extra variables or statements.
Click to reveal answer
In Kotlin, what can a try-catch block return when used as an expression?
✗ Incorrect
A try-catch expression returns the value from the try block if no exception occurs, or from the catch block if an exception is caught.
What must be true about the types returned by try and catch blocks in a try-catch expression?
✗ Incorrect
Both blocks must return compatible types so the overall expression has a consistent type.
How do you assign the result of a try-catch expression to a variable in Kotlin?
✗ Incorrect
You assign the whole try-catch expression directly to a variable using val result = try { ... } catch { ... }.
If no exception occurs in the try block, what does the try-catch expression return?
✗ Incorrect
If no exception occurs, the try block's value is returned as the result of the expression.
Why might you prefer try-catch as an expression over a traditional try-catch statement?
✗ Incorrect
Using try-catch as an expression lets you return fallback values directly, making code shorter and clearer.
Explain how try-catch works as an expression in Kotlin and why it is useful.
Think about how you can assign the result of try-catch to a variable.
You got /4 concepts.
Describe the type requirements for the try and catch blocks when used as an expression.
Consider what happens if try returns Int but catch returns String.
You got /3 concepts.