Kotlin – Throw Exception

Exceptions are thrown by JRE(Java Runtime Environment) at runtime. In addition to JRE, user can throw it explicitly for their own cause. User can throw inbuilt Exceptions like ArithmeticException, Exception, etc., or a custom built Exception.

Kotlin Throw – Syntax

To throw an exception to the calling method, use throw keyword.

The syntax to throw an exception is

</>
Copy
throw Exception(message : String)

message parameter of exception object thrown, is loaded with the the argument passed to Exception class.

Example 1 – Throw Exception in Kotlin

A basic example would be while validating some data. Say, while registering for some bank application that you have developed, user has to maintain a minimum balance of 1000. While validating the user’s amount, if you find that it is less than 1000, you may throw an exception to the calling method.

example.kt

</>
Copy
package exception_handling

fun main(args: Array<String>) {

    var amount = 600

    try {
        validateMinAmount(amount)
    } catch (e : Exception){
        println(e.message)
    }

}

fun validateMinAmount(amount : Int){
    throw Exception("Your balance $amount is less than minimum balance 1000.")
}

Output

Your balance 600 is less than minimum balance 1000.

Throw Custom Exception

If the code in try block could also throw another exceptions, it is a good practice to throw your own custom exceptions.

Create a kotlin file called CustomExceptions.kt.

CustomExceptions.kt

</>
Copy
class MinimumBalanceException(message: String) : Exception(message)

In the same location as that of the above file, create another Kotlin file named example.kt.

example.kt

</>
Copy
fun main(args: Array<String>) {

    var amount = 600

    try {
        validateMinAmount(amount)
    } catch (e : MinimumBalanceException){
        println(e.message)
    } catch (e : Exception){

    }

}

fun validateMinAmount(amount : Int){
    throw MinimumBalanceException("Your balance $amount is less than minimum balance 1000.")
}

Run this program, and you get the following output.

Output

Your balance 600 is less than minimum balance 1000.

Conclusion

In this Kotlin TutorialKotlin Throw Exception, we have learnt how to explicitly thrown an exception at runtime to the calling method.