Bird
Raised Fist0
Kotlinprogramming~10 mins

Throw as an expression in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Throw as an expression
Evaluate expression
↓
Is value valid?
No→Throw exception (expression ends here)
Yes↓
Use value in assignment or return
↓
Continue execution
Throw can be used as an expression to immediately stop and throw an exception, or to provide a value in expressions like assignments.
Execution Sample
Kotlin
val x = y ?: throw IllegalArgumentException("y is null")
println(x)
Assign y to x if not null; otherwise, throw an exception immediately.
Execution Table
StepExpression EvaluatedValue of yConditionActionResult
1Evaluate ynully != null?NoThrow IllegalArgumentException("y is null")
2Throw expression--Exception thrownProgram stops, no println executed
💡 y is null, so throw expression triggers exception and stops execution
Variable Tracker
VariableStartAfter 1Final
ynullnullnull
xuninitializeduninitializeduninitialized (exception thrown before assignment)
Key Moments - 2 Insights
Why does the program stop without printing anything?
Because at step 1 in the execution_table, y is null, so the throw expression runs and throws an exception, stopping the program before println.
Can throw be used inside an assignment?
Yes, as shown in the code, throw is used as an expression in the assignment to x, so if y is null, throw runs instead of assigning.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what happens at step 1 when y is null?
AThe throw expression is executed, throwing an exception
BThe value of y is assigned to x
CThe program prints the value of y
DThe condition y != null is true
💡 Hint
Check the 'Action' and 'Result' columns in step 1 of execution_table
According to variable_tracker, what is the value of x after step 1?
Anull
By's value
Cuninitialized because exception was thrown
DIllegalArgumentException
💡 Hint
Look at the 'Final' column for x in variable_tracker
If y was not null, how would the execution_table change?
AThrow expression would still run
Bx would be assigned y's value and println would execute
CProgram would stop immediately
DException would be thrown after println
💡 Hint
Think about the condition 'y != null?' and what happens when it is true in execution_table
Concept Snapshot
Throw as an expression in Kotlin:
- Can be used where a value is expected
- Example: val x = y ?: throw Exception()
- If condition fails, throw stops execution immediately
- Useful for concise null checks and error handling
- Acts like a value but actually throws an exception
Full Transcript
In Kotlin, throw can be used as an expression. This means you can use throw inside assignments or other expressions. For example, val x = y ?: throw IllegalArgumentException("y is null") means if y is not null, assign it to x; otherwise, throw an exception immediately. The execution flow checks y, and if null, runs the throw expression which stops the program. Variables like x remain uninitialized if throw runs. This lets you write concise code that handles errors right where values are expected.

Practice

(1/5)
1.

What does the throw keyword do when used as an expression in Kotlin?

easy
A. It declares a new variable.
B. It returns a value from a function.
C. It immediately stops execution and throws an exception.
D. It creates a new thread.

Solution

  1. Step 1: Understand the role of throw

    The throw keyword is used to signal an error by throwing an exception.
  2. Step 2: Recognize its effect in expressions

    When used as an expression, throw stops the current execution and throws the specified exception immediately.
  3. Final Answer:

    It immediately stops execution and throws an exception. -> Option C
  4. Quick Check:

    throw = stops and throws error [OK]
Hint: Throw always stops execution and signals an error [OK]
Common Mistakes:
  • Thinking throw returns a normal value
  • Confusing throw with return
  • Assuming throw creates variables
2.

Which of the following is the correct way to use throw as an expression in Kotlin?

val number = if (input > 0) input else ???
easy
A. throw IllegalArgumentException("Input must be positive")
B. return IllegalArgumentException("Input must be positive")
C. println("Input must be positive")
D. throw new Exception("Input must be positive")

Solution

  1. Step 1: Check Kotlin syntax for throw expression

    In Kotlin, throw is used without new keyword and can be used as an expression.
  2. Step 2: Match the correct usage in the if-else expression

    The correct syntax is throw IllegalArgumentException("message") without new and it fits as an expression in else branch.
  3. Final Answer:

    throw IllegalArgumentException("Input must be positive") -> Option A
  4. Quick Check:

    Throw expression syntax = throw IllegalArgumentException("Input must be positive") [OK]
Hint: Use throw without 'new' keyword in Kotlin [OK]
Common Mistakes:
  • Using 'new' keyword with throw
  • Using return instead of throw
  • Trying to print error instead of throwing
3.

What will be the output of this Kotlin code?

fun getName(name: String?): String {
    return name ?: throw IllegalArgumentException("Name required")
}

fun main() {
    println(getName(null))
}
medium
A. Compilation error
B. Name required
C. null
D. Exception in thread "main" java.lang.IllegalArgumentException: Name required

Solution

  1. Step 1: Analyze the Elvis operator with throw

    The expression name ?: throw IllegalArgumentException("Name required") returns name if not null, else throws the exception.
  2. Step 2: Check the input and output

    Since getName(null) is called, name is null, so the exception is thrown and program crashes with that message.
  3. Final Answer:

    Exception in thread "main" java.lang.IllegalArgumentException: Name required -> Option D
  4. Quick Check:

    Throw in Elvis operator throws exception [OK]
Hint: Elvis ?: with throw throws exception if left is null [OK]
Common Mistakes:
  • Expecting null to print
  • Thinking exception message prints normally
  • Assuming code compiles but returns empty string
4.

Identify the error in this Kotlin code snippet:

val age = 20
val validAge = if (age >= 18) age else throw "Age must be 18 or older"
medium
A. Cannot throw a String, must throw an Exception object.
B. The if expression is missing braces.
C. The variable age should be nullable.
D. The else branch should return a value, not throw.

Solution

  1. Step 1: Check the throw expression type

    In Kotlin, throw must throw an object of type Throwable, not a plain String.
  2. Step 2: Identify the error in else branch

    The code tries to throw a String literal, which is invalid and causes a compilation error.
  3. Final Answer:

    Cannot throw a String, must throw an Exception object. -> Option A
  4. Quick Check:

    Throw must be Exception, not String [OK]
Hint: Throw only Exception objects, not strings [OK]
Common Mistakes:
  • Throwing plain strings instead of exceptions
  • Missing braces but code compiles anyway
  • Confusing throw with return
5.

Given this Kotlin function:

fun parseNumber(input: String?): Int {
    val number = input?.toIntOrNull() ?: throw NumberFormatException("Invalid number")
    return number
}

What will parseNumber(null) do, and why is throw used as an expression here?

hard
A. Compiles but causes runtime error unrelated to throw.
B. Throws NumberFormatException because input is null; throw used to combine error and assignment.
C. Returns null because input is nullable; throw is a statement here.
D. Returns 0 because null converts to zero; throw is ignored.

Solution

  1. Step 1: Understand the Elvis operator with throw

    The expression input?.toIntOrNull() ?: throw NumberFormatException("Invalid number") tries to convert input to Int or throws if null or invalid.
  2. Step 2: Analyze behavior when input is null

    Since input is null, toIntOrNull() returns null, so the throw expression executes, throwing the exception immediately.
  3. Step 3: Reason why throw is used as expression

    Using throw as expression allows combining error handling with assignment in one line, making code concise and readable.
  4. Final Answer:

    Throws NumberFormatException because input is null; throw used to combine error and assignment. -> Option B
  5. Quick Check:

    Throw expression combines error and value assignment [OK]
Hint: Throw as expression lets you handle errors inline [OK]
Common Mistakes:
  • Thinking null converts to zero
  • Confusing throw as statement only
  • Ignoring exception thrown on null input
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