How to handle exceptions using try catch in Kotlin

Handling exceptions using try catch in Kotlin :

Exception handling is an important part of any software development. If there is even a little chance of exception, you should use try-catch block. That piece of code will not run, but it will not crash your application. Kotlin is mainly used for Android development. If you don’t use try catch handling, it will force quit your application. Exception handling in Kotlin is similar to Java. If you are coming from Java background, then it will be easy to understand. All exception are unchecked in Kotlin i.e. they are checked at the time of runtime.

Checked and unchecked exceptions :

Exceptions are categorized into two types : checked and unchecked.

  • Checked exceptions are checked at compile time e.g. FileNotFoundException.
  • Unchecked exceptions are checked at run time e.g. NullPointerException.

As mentioned above, we have only Unchecked exceptions in Kotlin. All are descendats of Throwable class.

Throwing an exception :

We can use throw to throw an exception. throw is an expression. For example:

fun main() {
    throw Exception("Exception in main")
}

It will throw one exception if you run the program:

Exception in thread "main" java.lang.Exception: Exception in main
	at ExampleKt.main(Example.kt:2)
	at ExampleKt.main(Example.kt)

Using a try-catch block:

We can wrap a piece of code that have the possibility to throw an exception in a try-catch block. The code is written inside the try block and catch block is used to handle the exception.

Below is the syntax of try-catch block :

try{
    // code that can throw exception
}catch(e: Exception){
    // handle the exception
}

Example of try-catch block:

Let’s take a look at the below program:

fun main() {
    try{
        var result = 1/0
    }catch(e: Exception){
        print("Exception detected")
    }
}

It will run and throw one ArithmeticException because we are dividing a number by 0. But the program will not stop this time. It will move to the catch block and print that message.

Multiple catch block:

We can have multiple catch blocks. For example, for the above example, we can add one more catch block as like below:

fun main() {
    try {
        var result = 1 / 0
    } catch (e1: ArithmeticException) {
        print("ArithmeticException detected")
    } catch (e: Exception) {
        print("Exception detected")
    }
}

Here, if any exception occurs inside the try block, it will first check the ArithmeticException block and then the second Exception block.

This program will print the below output:

Exception detected

finally block:

finally block is called at last. This is an optional block. If we add finally to the above program:

fun main() {
    try {
        var result = 1 / 0
    } catch (e1: ArithmeticException) {
        print("ArithmeticException detected")
    } catch (e: Exception) {
        print("Exception detected")
    } finally {
        print("\nInside finally block")
    }
}

It will print:

ArithmeticException detected
Inside finally block

Using try as expression:

try is an expression and it can return a value. The return value of try expression is either the last expression of the try block or if an exception occurs, it is the expression in the catch block.

fun main() {
    print("Enter a value :")
    val num = readLine()!!.toInt()
    val result = try {
        100 / num
    } catch (e: Exception) {
        null
    }
    print(result)
}

In this program, we are finding the result by dividing 100 by num. If it throws an Exception, e.g. if the value of num is 0, it will assign null to result.

Sample output:

Enter a value :10
10

Enter a value :0
null

Using throw as expression:

throw is an expression in kotlin and it is of type Nothing. We can use throw Exception or fail to throw an exception :

import kotlin.test.DefaultAsserter.fail

fun main() {
    print("Enter a value :")
    val num = readLine()!!.toInt()

    val result = if(num > 0) 100/num else fail("Invalid value")

    print(result)
}

Internally, fail throws one exception :

fun fail(message: String): Nothing {
    throw IllegalArgumentException(message)
}

You might also like:

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊