0
0
Kotlinprogramming~10 mins

Try-catch as an expression in Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to assign the result of the try block to the variable.

Kotlin
val result = try { 10 / 2 } catch (e: Exception) { 0 }
Drag options to blanks, or click blank then click option'
A(
B{
C[
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of curly braces for the try block.
Forgetting to open the try block with a brace.
2fill in blank
medium

Complete the code to catch an exception and return -1.

Kotlin
val result = try { 10 / 0 } catch ([1]: Exception) { -1 }
Drag options to blanks, or click blank then click option'
Ae
Berror
Cex
Dexception
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the variable name in the catch block.
Using invalid variable names.
3fill in blank
hard

Fix the error in the try-catch expression to avoid throwing an exception.

Kotlin
val result = try { 10 / [1] } catch (e: Exception) { 0 }
Drag options to blanks, or click blank then click option'
A0
B1
Cnull
D2
Attempts:
3 left
💡 Hint
Common Mistakes
Using zero as divisor causing ArithmeticException.
Using null which is not valid for division.
4fill in blank
hard

Complete the code to create a try-catch expression that returns the length of a string or -1 if null.

Kotlin
val length = try { input!!.length } catch (e: [1]) { -1 }
Drag options to blanks, or click blank then click option'
A{
BNullPointerException
CException
D(
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of braces for try block.
Catching the wrong exception type.
5fill in blank
hard

Fill both blanks to create a try-catch expression that returns the uppercase string or "ERROR" if exception occurs.

Kotlin
val output = try { input.toUpperCase() } catch (e: [1]) { [2] }
Drag options to blanks, or click blank then click option'
A{
BException
C"ERROR"
D(
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of braces for try block.
Returning a variable instead of a string literal on error.