Kotlin Exception Handling

Photo by Bram Naus on Unsplash

Kotlin Exception Handling

Try, catch, throw and finally

Introduction

An exception is an unwelcome or unexpected occurrence that occurs during program execution, i.e. at run time, and disturbs the usual flow of the program's instructions. Exception handling is a strategy for handling mistakes and preventing run-time crashes that can cause our program to crash.

Exceptions are classified into two types:

  • Checked Exception - Exceptions that are often set on methods and checked during compilation, such as IOException, FileNotFoundException, and so on.

  • Unchecked Exception - Exceptions that are typically caused by logical mistakes and are checked at run time, such as NullPointerException, ArrayIndexOutOfBoundException, and so on.

Exceptions in Kotlin

In Kotlin, we only have unchecked exceptions that can be caught only at run time. All exception classes are descended from the Throwable class.

In general, we use the throw-expression, to throw an exception object –

throw Exception("Throw me")

Examples of the common exceptions include:

  • NullPointerException: which is thrown when we try to invoke a property or method on null object.

  • ArrayIndexOutOfBoundException: which is thrown when we try to access invalid index value of an array.

  • Arithmetic Exception: which is thrown when invalid arithmetic operations are performed on numbers. for example division by zero.

  • SecurityException: It is thrown to indicate security violation.

For the example we are going to use an arithmetic exception

fun main(args : Array<String>){
    var num = 10 / 0     // throws exception
    println(num)
}

Output

Exception in thread "main" java.lang.ArithmeticException: / by zero

In the above program, we initialize the num variable with value 10/0, but we know in arithmetic divide by zero is not allowed. While we are trying to run the program it throws an exception.

To solve this problem, we have to use try-catch block.

In Kotlin, we utilize the try-catch block to handle exceptions in the program. The try block contains the code responsible for throwing an exception, while the catch block handles the exception. This block must be included in the main or other methods. Following a try block, either a catch block, a finally block, or both should be used.

Syntax for try-catch block –

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

Kotlin program of arithmetic exception handling using try-catch block –

import kotlin.ArithmeticException

fun main(args : Array<String>){
    try{
        var num = 10 / 0
    }
    catch(e: ArithmeticException){
        // caught and handles it
        println("Divide by zero not allowed")
    }
}

Output:

Divide by zero not allowed

In the above program, we have used try-catch block. The num variable which can throw exception is enclosed within the braces of try block because divide by zero not defined in arithmetic. The exception caught by the catch block and execute the println() statement.

Kotlin try-catch block as an expression

As we have seen, expressions always return a value. In our software, we can use the kotlin try-catch block as an expression. The expression's return value will be either the last expression of the try block or the last expression of the catch block. If there is an exception in the function, the catch block returns the value.

Kotlin program of using try-catch as an expression –

fun test(a: Int, b: Int) : Any {
    return try {
        a/b
        //println("The Result is: "+ a / b)
    }
    catch(e:Exception){
        println(e)
        "Divide by zero not allowed"
    }
}
// main function
fun main(args: Array<String>) {
    // invoke test function
    var result1 = test(10,2  ) //execute try block
    println(result1)
    var result = test(10,0 )   // execute catch block
    println(result)
}

Output:

5
java.lang.ArithmeticException: / by zero
Divide by zero not allowed

In the above code, we have used try-catch as an expression. Declare a function test on the top of program and it return a value using try-catch block. We have invoked the test function from main method and passed the parameter values (10,2) The test function evaluate the arguments and return try value (10/2 = 5). But in next call, we passed (b=0) and this time exception is caught and returns expression of catch block.

Kotlin throw keyword –

In Kotlin, we use throw keyword to throw an explicit exception. It can also be used to throw a custom exception.

Kotlin program of using throw keyword –

fun main(args: Array<String>) {
    test("abcd")
    println("executes after the validation")
}
fun test(password: String) {
    // calculate length of the entered password and compare
    if (password.length < 6)
        throw ArithmeticException("Password is too short")
    else
        println("Strong password")
}

Output:

Exception in thread "main" java.lang.ArithmeticException: Password is too short

Kotlin finally block

In Kotlin, finally block is always executes irrespective of whether an exception is handled or not by the catch block. So it is used to execute important code statement. We can also use finally block with try block and skip the catch block from there.

Syntax of finally block with try block –

try {
   // code that can throw exception
} finally {
   // finally block code
}

Kotlin program of using finally block with try block block –

fun main(args : Array<String>){
    try{
        var ar = arrayOf(1,2,3,4,5)
        var int = ar[6]
        println(int)
    }
  finally {
        println("This block always executes")
    }
}

Output:

This block always executes
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 5

In the above program, we have used try with finally block and skipped the catch block. Here, exception is not handled by catch block but executes the finally block.