Exception Handling in Kotlin

A guide on implementing exception handling in Kotlin to avoid runtime issues in your application.

Introduction

Exception handling is important in practically all programming languages, specifically Kotlin. This function has made it feasible to handle errors in our mobile application without crashing. This article explains the concept of exception handling and its importance to software developers. In this article, you will also learn how to implement exception handling in Kotlin.

Prerequisite

To gain knowledge from this guide you should have a basic understanding of Kotlin such as declaring properties, functions, and OOP. If you are not familiar with these concepts mentioned, I recommend learning them before proceeding. You must have your IDE(IntelliJ or Android Studio) already installed on your PC.

What is an Exception

Exception is a runtime problem that occurs in a program and leads to program termination. This event interrupts the normal flow of program execution, causing run-time errors and even crashing the program. A Runtime error is thrown while the program is already running.

Examples of exceptions are:

  • Running out of memory

  • Array out of bound

  • Divided by zero

In handling this type of problem during program execution, exception handling is used.

What is exception handling?

Exception handling is a method that handles runtime problems and maintains the flow of program execution. When exception handling is used, exceptions may still arise but they will not make your program crash. Your program may still work even though it might not do things as intended.

Kotlin's exception-handling mechanism provides developers with a clear and concise way to handle exception scenarios, making it easier to identify, isolate, and handle errors, which ultimately leads to improved software quality and user experience.

For example, if you try to access the internet and you don't handle the exception that the internet connection won't work then you will run into an error. So you will have to handle the exception by displaying a text to the user to turn on their internet.

Why is exception Handling important in Kotlin?

Exception Handling is very crucial to all programming languages specifically Kotlin

The importance of exception handling cannot be over-emphasized. Here are some of the importance listed:

  1. It enables the normal execution of a program.

  2. It enables software developers to debug their code effectively.

  3. It helps in the smooth running of the application to avoid crashing.

  4. It allows developers to write clean and maintainable code.

Keywords used in Exception Handling

Four different keywords are used in exception handling:

Try: the try block holds a set of statements that might generate an exception. Either the catch or finally or both must come after it. For example getting an internet connection.

Catch: the exception that the try block throws is caught by the catch block. So if there is an exception in the try block the catch block should execute otherwise it will not execute. In the case of the internet connection if there is an error which is no internet connection in the try block the catch block will execute.

Finally: finally block always executes whether the exception is handled or not. So it is used to execute important code statements (like closing buffers). For example, closing a buffer which takes care of the connection to the internet.

Throw: To throw an exception explicitly the throw keyword is used.

Types of Exceptions

Unchecked exception: unchecked exceptions are thrown as a result of coding errors. This type of exception inherits(extends) from the Runtime. The Unchecked exception is checked at runtime which means when our app is running and not during compile time. Examples of unchecked exceptions are:

  • Arithmetic Exception: are thrown when we divide a number by 0.

  • ArrayIndexOutOfBound: is thrown when an array has been tried to access with an incorrect index value. Let's say the array has only 6 values and you are trying to access the value at index 7 this will throw the ArrayIndexOutOf bound exception.

  • Security Exception: thrown by the security manager to indicate a security violation. e.g. trying to access the GPS but the user doesn't give us the right to use the GPS functionality.

  • NullPointerException: thrown when invoking a method or property or a non-null object. e.g. trying to access an object that is null.

CheckedException: A Checked exception is checked at compile time. This exception type extends the Throwable class. Example of checked Exception.

  • Input/output (IO) Exception.

  • Sequel (SQL)Exception.

Try - Catch block and its syntax

The try-catch block method handles the exceptions that arise in the code. Syntax of the try-catch block:

try{
//code that may throw exception

}catch(e: Arithmetic Exception){

//code that handles the exception 

    }

Example with Exception Handling

fun main(){
val x = getNumber("15.5")
//the variable y is trying to get an Int value of 15.5 (which is a double value)
println(x)
}
fun getNumber(y:String):Int{

return try{
Integer.parseInt(y)
//return y as Int
}catch(e: NumberFormatException){

0
}
}
//Output is 0

Multiple catch Block and it Syntax

We can use multiple catch blocks in your code. Multiple catch blocks are used when using different types of operation in your try block which may cause different exceptions in the try block.

Here is the syntax for multiple catch block

fun main(){
try{

//
}catch(e:ArithmeticException){
//
}catch(e: NumberFormatException){
//
}catch(e: ArrayIndexOutOfBoundsException){
//
}catch(e: Exception){
//
}
}

Example with the multiple-catch block

fun main() {
try {
val x = IntArray(5)
println(x[5])

}catch(e: ArithmeticException){
println("arithmetic exception")
//
}catch(e: NumberFormatException){
println ("number format exception")
//
}catch(e: ArrayIndexOutOfBoundsException){
println ("ArrayIndexOutOfBoundsException")
//
}catch(e: Exception){
println ("parent exception")
//
}
println("practicing with multiple catch blocks")
}
//Output

/*

*ArrayIndexOutOfBoundsException

Nested try-catch block and its syntax

We can also use nested try blocks when required. The requirement of nested try-catch blocks arises when a block of code generates an exception, and within that block, another code statement also generates another exception.

fun main(){
try{
//code block
try{
//code block
}catch(e:someException){
//exception

}catch(e: someException){
//exception
}
}

Finally block

Such a block which is used whether exceptions are handled or not . So it is used to execute important code statements.

Example with the Finally Block

fun main() {
val x = getNumber("10.5") 
//the variable y is trying to get an Int value of 10.5 (which is a double value)
println(x)
}
fun getNumber(y:String):Int{
return try{
Integer.parseInt(y)
//return str as Int
}catch(e: NumberFormatException){
0
} finally {
println("must print")
}
}
// Output
// must print
// 0

Throw keyword

To throw an explicit exception use the throw keyword.

  • It is also used to throw a custom exception.

  • It is also used to throw an exception object.

Syntax of the throw keyword

throw ArithmeticException

Example with the throw keyword

fun main() {
checkAge (17)
}
fun checkAge(age: Int){
when (age){

in 15..18 -> throw ArithmeticException("under age")
in 19..30 -> println("adult")
else -> println("enter valid age")

}
}//output: java.lang.ArithmeticException: under age

Conclusion

In this article, you have learned extensively in detail how to handle exceptions in Kotlin and as a software developer, you should be able to handle errors when writing codes. By using try-catch blocks, developers can gracefully handle exceptions without resorting to tedious error-checking conditions, resulting in more readable and efficient code. To learn more about the Kotlin programming language here is a resource for you Kotlin documentation.