Error handling helps your app stay safe and friendly when something goes wrong. It stops crashes and shows helpful messages.
When reading data from the internet that might fail
When opening a file that might not exist
When converting user input to numbers
When calling a function that might throw an error
When working with databases that might have issues
Syntax
Android Kotlin
try {
// code that might cause an error
} catch (e: ExceptionType) {
// code to handle the error
} finally {
// code that runs no matter what
}
try block contains code that might cause an error.
catch block handles the error if it happens.
Examples
This catches an error when converting text to a number.
Android Kotlin
try {
val number = "abc".toInt()
} catch (e: NumberFormatException) {
println("Not a valid number")
}
This handles errors when reading a file.
Android Kotlin
import java.io.File
import java.io.IOException
try {
val file = File("path/to/file.txt")
val text = file.readText()
} catch (e: IOException) {
println("File not found or cannot read")
}
finally runs no matter if error happened or not.
Android Kotlin
try {
val result = riskyOperation()
} catch (e: Exception) {
println("Something went wrong")
} finally {
println("This always runs")
}
Sample App
This program tries to convert a string to a number. If it fails, it shows an error message. It always prints a done message at the end.
Android Kotlin
fun main() {
try {
val input = "123a"
val number = input.toInt()
println("Number is $number")
} catch (e: NumberFormatException) {
println("Error: '$input' is not a number.")
} finally {
println("Done checking input.")
}
}
OutputSuccess
Important Notes
Always catch specific exceptions to handle errors clearly.
Use finally to clean up resources like closing files or connections.
Don't ignore errors; show messages or fix problems to keep users happy.
Summary
Error handling keeps apps safe and user-friendly.
Use try-catch blocks to catch and fix errors.
finally runs code no matter what, useful for cleanup.
Practice
(1/5)
1. What is the main purpose of a try-catch block in Kotlin error handling?
easy
A. To style the user interface
B. To speed up the app execution
C. To create new variables
D. To catch exceptions and prevent app crashes
Solution
Step 1: Understand the role of try-catch
The try block contains code that might cause an error, and the catch block handles that error.
Step 2: Identify the purpose in app safety
Using try-catch prevents the app from crashing by catching exceptions and allowing graceful handling.
Final Answer:
To catch exceptions and prevent app crashes -> Option D
Quick Check:
Error handling = catch exceptions [OK]
Hint: Try-catch blocks catch errors to keep apps running [OK]
Common Mistakes:
Thinking try-catch speeds up code
Confusing try-catch with UI styling
Believing try-catch creates variables
2. Which of the following is the correct syntax to catch an exception in Kotlin?
Kotlin does not allow assigning null to a non-nullable type without using nullable type syntax.
Step 2: Check compilation rules
Assigning null to val text without declaring it nullable causes a compile-time error.
Final Answer:
Code will not compile due to null assignment -> Option A
Quick Check:
Null safety requires nullable types [OK]
Hint: Null must be assigned to nullable type with ? [OK]
Common Mistakes:
Assuming NullPointerException is caught at runtime
Ignoring Kotlin's null safety rules
Thinking code runs without error
5. You want to read a file and always close it after reading, even if an error occurs. Which Kotlin error handling pattern is best to ensure the file closes properly?
hard
A. Use try block only
B. Use try-catch-finally and close file in finally
C. Use try-catch without finally
D. Use only finally block
Solution
Step 1: Understand resource cleanup needs
Files must be closed to free resources, even if an error happens during reading.
Step 2: Use finally block for guaranteed execution
The finally block runs no matter what, so closing the file there ensures cleanup.
Step 3: Combine with try-catch for error handling
Try-catch handles errors, finally ensures file closure regardless of success or failure.
Final Answer:
Use try-catch-finally and close file in finally -> Option B
Quick Check:
Finally block ensures cleanup [OK]
Hint: Put cleanup code in finally block to always run [OK]
Common Mistakes:
Closing file only in try block
Ignoring finally block for cleanup
Using finally without try-catch
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.