📖 Scenario: Imagine you are making a simple calculator app that divides two numbers. Sometimes, users might enter zero as the divisor, which causes an error. We want to handle this error nicely so the app doesn't crash and shows a friendly message instead.
🎯 Goal: Build a Kotlin program that divides two numbers and uses error handling to catch division by zero errors, then shows a clear message.
📋 What You'll Learn
Create two variables for numbers to divide
Add a variable to hold the result
Use a try-catch block to handle division by zero
Print the result or an error message
💡 Why This Matters
🌍 Real World
Handling errors prevents apps from crashing and helps users understand what went wrong.
💼 Career
Error handling is a key skill for developers to write reliable and user-friendly software.
Progress0 / 4 steps
1
Create two number variables
Create two variables called numerator and denominator with values 10 and 0 respectively.
Kotlin
Hint
Use val to create variables and assign the exact numbers.
2
Create a variable for the result
Create a variable called result of type Double? and set it to null.
Kotlin
Hint
Use var because the result will change later. Use Double? to allow null.
3
Use try-catch to handle division
Write a try block that divides numerator by denominator and assigns it to result. Add a catch block to catch ArithmeticException and print "Cannot divide by zero!".
Kotlin
Hint
Use try and catch to handle errors. Perform division with doubles to avoid integer division issues, catching the exception if denominator is zero.
4
Print the result if no error
After the try-catch block, write an if statement that checks if result is not null. If so, print "Result: " followed by the result value.
Kotlin
Hint
Check if result is not null before printing it.
Practice
(1/5)
1. Why is error handling important in Kotlin programs?
easy
A. It helps keep the program running smoothly even when errors occur.
B. It makes the program run faster by skipping checks.
C. It removes the need to write any code for errors.
D. It automatically fixes all bugs without programmer input.
Solution
Step 1: Understand the purpose of error handling
Error handling is used to manage unexpected problems during program execution.
Step 2: Identify the benefit of error handling
It helps the program continue running safely and informs the user about issues.
Final Answer:
It helps keep the program running smoothly even when errors occur. -> Option A
Quick Check:
Error handling = program safety and stability [OK]
Hint: Error handling keeps programs safe and user-friendly [OK]
Common Mistakes:
Thinking error handling speeds up code
Believing error handling fixes bugs automatically
Assuming error handling removes all code for errors
2. Which Kotlin syntax correctly starts a block to catch exceptions?
easy
A. catch (Exception e) { ... } try { ... }
B. try { ... } catch (e: Exception) { ... }
C. try (e: Exception) { ... } catch { ... }
D. catch { ... } try (e: Exception) { ... }
Solution
Step 1: Recall Kotlin error handling syntax
Kotlin uses try to start a block and catch (e: Exception) to handle errors.
fun main() {
try {
val result = 10 / 0
println(result)
} catch (e: ArithmeticException) {
println("Error caught: Division by zero")
}
}
medium
A. 10
B. Program crashes with exception
C. 0
D. Error caught: Division by zero
Solution
Step 1: Analyze the try block
The code attempts to divide 10 by 0, which causes an ArithmeticException.
Step 2: Check the catch block
The catch block catches ArithmeticException and prints the error message.
Final Answer:
Error caught: Division by zero -> Option D
Quick Check:
Division by zero triggers catch = prints error message [OK]
Hint: Division by zero triggers catch block printing error [OK]
Common Mistakes:
Expecting program to print 10 or 0
Thinking program crashes without catch
Ignoring exception type in catch
4. Identify the error in this Kotlin code snippet:
fun main() {
try {
val text = "abc"
val number = text.toInt()
} catch e: NumberFormatException {
println("Invalid number")
}
}
medium
A. Missing parentheses around exception in catch block
B. Using toInt() on a string is not allowed
C. try block should not have braces
D. println statement is outside catch block
Solution
Step 1: Check catch block syntax
Kotlin requires parentheses around the exception in catch: catch (e: Exception).
Step 2: Identify the error
The code uses catch e: NumberFormatException without parentheses, causing syntax error.
Final Answer:
Missing parentheses around exception in catch block -> Option A
Quick Check:
Catch syntax needs parentheses [OK]
Hint: Catch exception must be in parentheses (e: Exception) [OK]
Common Mistakes:
Omitting parentheses in catch
Thinking toInt() is invalid on strings
Misplacing println outside catch
5. You want to read an integer from user input safely in Kotlin. Which approach best handles invalid input without crashing?
fun readInt(): Int {
// Your code here
}
hard
A. Use if (readLine() is Int) return readLine()!! else return 0
B. Directly call readLine()!!.toInt() without try-catch
C. Use try { readLine()!!.toInt() } catch (e: Exception) { 0 } to return 0 on error
D. Ignore errors and assume input is always valid
Solution
Step 1: Understand safe input reading
Using try-catch allows catching exceptions from invalid input conversion.
Step 2: Evaluate options
Use try { readLine()!!.toInt() } catch (e: Exception) { 0 } to return 0 on error uses try-catch to convert input safely and returns 0 if conversion fails.
Final Answer:
Use try { readLine()!!.toInt() } catch (e: Exception) { 0 } to return 0 on error -> Option C
Quick Check:
Try-catch safely handles input errors [OK]
Hint: Wrap input conversion in try-catch to avoid crashes [OK]
Common Mistakes:
Not using try-catch for input conversion
Assuming input is always valid
Using incorrect type checks on readLine()
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.