Kotlin Exception Handling | try, catch, throw and finally

An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions. Exception handling is a technique, using which we can handle errors and prevent run time crashes that can stop our program.

There are two types of Exceptions –

  1. Checked Exception – Exceptions that are typically set on methods and checked at the compile time, for example IOException, FileNotFoundException etc
  2. UnChecked Exception – Exceptions that are generally due to logical errors and checked at the run time, for example NullPointerException, ArrayIndexOutOfBoundException etc

Kotlin Exceptions –

In Kotlin, we have only unchecked exceptions and can be caught only at run time. All the exception classes are descendants of Throwable class.

We generally use the throw-expression, to throw an exception object –

throw Exception("Throw me")

Some of the common exceptions are:

  • NullPointerException: It is thrown when we try to invoke a property or method on null object.
  • Arithmetic Exception: It is thrown when invalid arithmetic operations are performed on numbers. eg – divide by zero.
  • SecurityException: It is thrown to indicate security violation.
  • ArrayIndexOutOfBoundException: It is thrown when we try to access invalid index value of an array.

Kotlin program of throwing arithmetic exception –

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

Kotlin try-catch block –

In Kotlin, we use try-catch block for exception handling in the program. The try block encloses the code which is responsible for throwing an exception and the catch block is used for handling the exception. This block must be written within the main or other methods. Try block should be followed by either catch block or finally block or both.

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 –

filter_none

edit
close

play_arrow

link
brightness_4
code

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")
    }
}

chevron_right


Output:

Divide by zero not allowed

Explanation:
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 already know, expression always returns a value. We can use kotlin try-catch block as an expression in our program. The value returned by the expression will be either last expression of try block or last expression of catch block. If an exception occurs in the code, then catch block returns the value.

Kotlin program of using try-catch as an expression –

filter_none

edit
close

play_arrow

link
brightness_4
code

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)
}

chevron_right


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 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 –

filter_none

edit
close

play_arrow

link
brightness_4
code

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")
    }
}

chevron_right


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.

Syntax of finally block with try-catch block –

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

We can also use try, catch and finally blocks all together.
Kotlin program of using finally block with try-catch block-

filter_none

edit
close

play_arrow

link
brightness_4
code

fun main (args: Array<String>){  
    try {  
        var int = 10 / 0  
        println(int)  
    } catch (e: ArithmeticException) {  
        println(e)  
    } finally {  
        println("This block always executes")  
    }  
}  

chevron_right


Output:

java.lang.ArithmeticException: / by zero
This block always executes

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 –

filter_none

edit
close

play_arrow

link
brightness_4
code

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")
}

chevron_right


Output:

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.