Skip to content
Related Articles

Related Articles

Improve Article
Kotlin Exception Handling | try, catch, throw and finally
  • Last Updated : 25 Jun, 2019

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 –




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.

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 –




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

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 –




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

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-




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

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 –




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
My Personal Notes arrow_drop_up
Recommended Articles
Page :