0
0
Kotlinprogramming~5 mins

Try-catch as an expression in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
ANothing, it cannot return a value
BOnly a Boolean value
CA value from either the try or catch block
DOnly the exception object
What must be true about the types returned by try and catch blocks in a try-catch expression?
AThey must be compatible types
BThey can be any unrelated types
COnly the try block returns a value
DOnly the catch block returns a value
How do you assign the result of a try-catch expression to a variable in Kotlin?
Atry { val result = ... } catch { ... }
Bval result = try { ... } catch (e: Exception) { ... }
Cval result; try { ... } catch { ... }
Dtry { ... } catch { ... } = val result
If no exception occurs in the try block, what does the try-catch expression return?
AAn exception
BThe value from the catch block
CNull
DThe value from the try block
Why might you prefer try-catch as an expression over a traditional try-catch statement?
AIt allows returning fallback values directly and reduces extra code
BIt runs faster
CIt catches more exceptions
DIt disables exceptions
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.