Kotlin Error Handling and Exceptions
Course Title: Kotlin Programming: From Basics to Advanced Techniques
Section Title: Error Handling and Exceptions
Topic: Write Kotlin code that demonstrates proper error handling and exception management.(Lab topic)
Introduction
In this lab topic, we will write Kotlin code that demonstrates proper error handling and exception management. We have learned about error handling and exceptions in Kotlin, including try-catch blocks, finally blocks, creating custom exceptions, and best practices for error handling. Now, it's time to put our knowledge into practice.
Lab Exercise: Proper Error Handling and Exception Management
For this lab exercise, we will create a Kotlin program that performs the following operations:
- Reads a file from disk.
- Parses the file content into JSON.
- Calculates the sum of a field in the JSON data.
Here's the sample JSON data:
[
{
"name": "John",
"age": 30,
"salary": 5000.0
},
{
"name": "Jane",
"age": 25,
"salary": 6000.0
},
{
"name": "Jim",
"age": 40,
"salary": 7000.0
}
]
The goal is to calculate the total salary of all employees.
Step 1: Create a Custom Exception Class
First, let's create a custom exception class called JsonParsingException
that will be used when we encounter an error parsing JSON:
// JsonParsingException.kt
class JsonParsingException(message: String) : Exception(message)
Step 2: Write a Function to Read a File
Next, let's write a function that reads a file from disk:
// FileUtil.kt
import java.io.File
import java.io.FileNotFoundException
fun readFileContent(file: File): String {
try {
return file.readText()
} catch (e: FileNotFoundException) {
throw JsonParsingException("File not found: ${file.path}")
}
}
In the readFileContent
function, we're reading the file content using the readText
method and returning it as a String
. If the file is not found, we're catching the FileNotFoundException
and throwing our custom JsonParsingException
with a meaningful error message.
Step 3: Write a Function to Parse JSON
Now, let's write a function that parses JSON data into a list of employee objects:
// Employee.kt
data class Employee(val name: String, val age: Int, val salary: Double)
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
fun parseJson(jsonContent: String): List<Employee> {
try {
val gson = Gson()
return gson.fromJson(jsonContent, Array<Employee>::class.java).toList()
} catch (e: JsonSyntaxException) {
throw JsonParsingException("Failed to parse JSON: $jsonContent")
}
}
In the parseJson
function, we're using the Google Gson library to parse the JSON data into a list of Employee
objects. If the JSON data is invalid, we're catching the JsonSyntaxException
and throwing our custom JsonParsingException
with a meaningful error message.
Step 4: Write a Function to Calculate the Total Salary
Next, let's write a function that calculates the total salary of all employees:
// Calculator.kt
fun calculateTotalSalary(employees: List<Employee>): Double {
return employees.sumByDouble { it.salary }
}
In the calculateTotalSalary
function, we're using the sumByDouble
method to calculate the total salary of all employees.
Step 5: Write the Main Function
Finally, let's write the main function that reads a file, parses JSON, and calculates the total salary:
// Main.kt
fun main() {
try {
val file = File("employees.json")
val jsonContent = readFileContent(file)
val employees = parseJson(jsonContent)
val totalSalary = calculateTotalSalary(employees)
println("Total salary: $totalSalary")
} catch (e: JsonParsingException) {
println("Error: ${e.message}")
} catch (e: Exception) {
println("Error: ${e.message}")
}
}
In the main function, we're reading a file, parsing JSON, calculating the total salary, and printing the result. We're also catching any exceptions that might occur and printing an error message.
Conclusion
In this lab exercise, we demonstrated proper error handling and exception management in Kotlin. We created a custom exception class, wrote functions to read a file, parse JSON, and calculate the total salary, and wrote a main function that handles exceptions and prints an error message.
What to Do Next?
You can modify the code to handle different types of exceptions and add additional logging or error handling mechanisms.
If you have any questions or need help, please leave a comment below or ask for help.
Additional Resources
- Kotlin Exception Handling Documentation
- Kotlin Coroutines Documentation
- Google Gson Library Documentation
Example Code
You can find the complete example code for this lab exercise in the attached zip file.
Example Use Cases
- Reading and parsing JSON data from a file or API.
- Handling exceptions and errors in a robust and maintainable way.
- Creating custom exception classes to represent domain-specific errors.
By following the instructions and code examples in this lab exercise, you can create robust and maintainable Kotlin programs that handle exceptions and errors properly.
Next topic: We will explore Introduction to coroutines: concepts and benefits in the Coroutines and Asynchronous Programming section.
Images

Comments