Handling Exceptions with Multiple Catch Blocks in Kotlin
📖 Scenario: Imagine you are writing a small Kotlin program that reads numbers from a list and divides 100 by each number. Sometimes, the numbers might cause errors like division by zero or invalid input. You want to handle these errors properly.
🎯 Goal: You will create a Kotlin program that uses multiple catch blocks to handle different types of exceptions separately.
📋 What You'll Learn
Create a list of integers with the exact values: 10, 0, 5, -2
Create a variable called result to store the division result
Use a try block to divide 100 by each number in the list
Use multiple catch blocks to handle ArithmeticException and Exception
Print the result or the error message for each division
💡 Why This Matters
🌍 Real World
Handling different errors separately helps programs run smoothly without crashing. For example, apps that process user input or files often need multiple catch blocks.
💼 Career
Understanding exception handling with multiple catch blocks is important for writing robust Kotlin applications in software development jobs.
Progress0 / 4 steps
1
Create the list of numbers
Create a list called numbers with these exact integer values: 10, 0, 5, and -2.
Kotlin
Hint
Use listOf() to create a list with the given numbers.
2
Create a variable to store the result
Create a variable called result of type Int and initialize it to 0.
Kotlin
Hint
Use var to create a variable that can change later.
3
Use try and multiple catch blocks to handle exceptions
Write a for loop that goes through each number in numbers. Inside the loop, use a try block to divide 100 by the number and store it in result. Add two catch blocks: one for ArithmeticException and one for general Exception. In each catch, print a message describing the error.
Kotlin
Hint
Remember to use for (number in numbers) to loop. Use try to attempt division. Catch ArithmeticException first, then general Exception.
4
Print the final output
Run the program to print the result of dividing 100 by each number or the error messages from the catch blocks.
Kotlin
Hint
Just run the program. The output should show results or error messages for each number.
Practice
(1/5)
1. What is the main purpose of using multiple catch blocks in Kotlin?
easy
A. To avoid using the try keyword
B. To run multiple try blocks at once
C. To handle different types of exceptions separately
D. To make the program run faster
Solution
Step 1: Understand exception handling
Multiple catch blocks allow handling different exceptions in different ways.
Step 2: Compare options
Only To handle different types of exceptions separately correctly describes handling different exception types separately.
Final Answer:
To handle different types of exceptions separately -> Option C