How to rethrow an exception in Kotlin

How to rethrow an exception in Kotlin :

In Kotin, we can use one try-catch-finally block to handle an exception. try block handles the code and if any exception occurs, it moves to the catch block and at last, finally block. Rethrowing an exception means rethrow an exception again in the catch block. The first thing that comes to our mind is that why we need to rethrow an exception since we are already handling it in the catch block. It is because, sometimes, we may need to handle all exceptions except a few specific exceptions, and for that specific exceptions, we can have separate catch blocks and rethrow those exceptions from there.

To rethrow an exception, we use throw exception.

For example,

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

    try{
        val result = 1000/num;
    }catch(e: ArithmeticException){
        throw e
    }catch(ex: Exception){
        print("Exception is caught")
    }
}

Here, we are rethrowing the exception, if it is an ArithmeticException. For other types of exceptions, we are printing one message.

You might also like: