Bird
Raised Fist0
Kotlinprogramming~10 mins

Try-catch as an expression in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Try-catch as an expression
Start
↓
Try block runs
↓
No Exception?
Yes→Try result used
↓
End
↓
Exception?
Yes→Catch block runs
↓
Catch result used
↓
End
The try block runs first. If no exception occurs, its result is used. If an exception happens, the catch block runs and its result is used instead.
Execution Sample
Kotlin
val result = try {
    "123".toInt()
} catch (e: NumberFormatException) {
    -1
}
println(result)
This code tries to convert a string to an integer. If it fails, it catches the exception and returns -1 instead.
Execution Table
StepActionEvaluationResult
1Execute try block: "123".toInt()No exception123
2Assign try block result to 'result'result = 123123
3Print 'result'Output123
💡 Try block succeeded, no exception thrown, result is 123
Variable Tracker
VariableStartAfter Step 1After Step 2Final
resultuninitializeduninitialized123123
Key Moments - 2 Insights
Why does the catch block not run when the string is "123"?
Because the try block converts "123" to integer successfully without throwing an exception, as shown in execution_table step 1.
What happens if the string cannot be converted to an integer?
The try block throws a NumberFormatException, so the catch block runs and returns -1 instead, replacing the try block result.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'result' after step 2?
A123
B-1
Cuninitialized
DException
💡 Hint
Check the 'Assign try block result to result' row in the execution_table.
At which step does the program print the output?
AStep 1
BStep 3
CStep 2
DNo print occurs
💡 Hint
Look for the 'Print result' action in the execution_table.
If the string was "abc" instead of "123", what would happen?
AProgram crashes without catch
BTry block returns "abc"
CCatch block runs and result is -1
DResult remains uninitialized
💡 Hint
Recall that "abc" cannot convert to Int, so exception triggers catch block.
Concept Snapshot
Try-catch in Kotlin can be used as an expression.
Syntax:
val result = try { /* code */ } catch(e: Exception) { /* fallback */ }
If try succeeds, its value is used.
If try throws, catch value is used instead.
This allows safe assignment with error handling in one expression.
Full Transcript
In Kotlin, try-catch can be used as an expression that returns a value. The try block runs first. If it completes without error, its result is assigned. If an exception occurs, the catch block runs and its result is assigned instead. For example, converting a string to an integer inside try returns the number if successful. If conversion fails, catch returns -1. This way, you can safely assign a value with error handling in one line. The execution table shows each step: running try, assigning result, and printing output. Variables track the value changes. Key moments clarify why catch runs only on exceptions. The quiz tests understanding of these steps and outcomes.

Practice

(1/5)
1. What does it mean that try-catch is an expression in Kotlin?
easy
A. It can only be used inside functions with no return type.
B. It only catches exceptions but cannot return values.
C. It must always be followed by a finally block.
D. It can return a value that can be assigned to a variable.

Solution

  1. Step 1: Understand try-catch as an expression

    In Kotlin, try-catch can produce a value, unlike in some languages where it is only a statement.
  2. Step 2: Recognize value assignment

    This means you can assign the result of a try-catch block directly to a variable.
  3. Final Answer:

    It can return a value that can be assigned to a variable. -> Option D
  4. Quick Check:

    Try-catch returns value = D [OK]
Hint: Try-catch can be assigned like any expression [OK]
Common Mistakes:
  • Thinking try-catch cannot return values
  • Confusing try-catch with only statements
  • Believing finally is always required
2. Which of the following is the correct syntax to assign a value using try-catch as an expression in Kotlin?
easy
A. val result = try { 10 / 0 } catch (e: Exception) { 0 }
B. val result try { 10 / 0 } catch (e: Exception) { 0 }
C. val result = try { 10 / 0 } finally { 0 }
D. val result = catch (e: Exception) { 0 } try { 10 / 0 }

Solution

  1. Step 1: Check assignment syntax

    The correct way to assign a value from try-catch is using val result = try { ... } catch { ... }.
  2. Step 2: Validate each option

    val result = try { 10 / 0 } catch (e: Exception) { 0 } uses correct syntax with try-catch returning a value. Options A, B, and D have syntax errors or misuse of finally/catch.
  3. Final Answer:

    val result = try { 10 / 0 } catch (e: Exception) { 0 } -> Option A
  4. Quick Check:

    Correct try-catch assignment syntax = C [OK]
Hint: Remember: val x = try { } catch { } [OK]
Common Mistakes:
  • Omitting '=' in assignment
  • Using finally block to return value
  • Placing catch before try
3. What will be the output of this Kotlin code?
val result = try {
    val num = 10 / 2
    "Success: $num"
} catch (e: Exception) {
    "Error"
}
println(result)
medium
A. Error
B. Success: 5
C. 10 / 2
D. Exception thrown

Solution

  1. Step 1: Evaluate try block

    The division 10 / 2 equals 5, so the try block returns the string "Success: 5".
  2. Step 2: Check for exceptions

    No exception occurs, so the catch block is skipped.
  3. Final Answer:

    Success: 5 -> Option B
  4. Quick Check:

    Try succeeds, output = Success: 5 [OK]
Hint: If no error, try block value is returned [OK]
Common Mistakes:
  • Assuming catch runs even without error
  • Printing the expression instead of result
  • Confusing integer division with string output
4. Identify the error in this Kotlin code using try-catch as an expression:
val result = try {
    val x = 10 / 0
    x
} catch {
    0
}
println(result)
medium
A. Cannot assign try-catch to a val
B. Division by zero is allowed without catch
C. Missing exception parameter in catch block
D. println cannot print variables from try-catch

Solution

  1. Step 1: Check catch block syntax

    The catch block must declare an exception parameter like catch (e: Exception).
  2. Step 2: Identify the error

    Here, catch is missing the exception parameter, causing a syntax error.
  3. Final Answer:

    Missing exception parameter in catch block -> Option C
  4. Quick Check:

    Catch needs exception parameter = B [OK]
Hint: Always include exception variable in catch (e: Exception) [OK]
Common Mistakes:
  • Omitting exception parameter in catch
  • Ignoring division by zero error
  • Thinking try-catch can't be assigned
5. Given this Kotlin function using try-catch as an expression, what will parseIntOrZero("abc") return?
fun parseIntOrZero(input: String): Int = try {
    input.toInt()
} catch (e: NumberFormatException) {
    0
}
hard
A. Returns 0
B. Throws NumberFormatException
C. Returns null
D. Returns input string

Solution

  1. Step 1: Analyze try block behavior

    Calling input.toInt() on "abc" throws NumberFormatException.
  2. Step 2: Catch block returns fallback

    The catch block catches this exception and returns 0 as fallback.
  3. Final Answer:

    Returns 0 -> Option A
  4. Quick Check:

    Exception caught, fallback 0 returned = A [OK]
Hint: Catch returns fallback value on error [OK]
Common Mistakes:
  • Expecting exception to propagate
  • Thinking null is returned on error
  • Confusing return type with input type
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard