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 and syntax of throwing an exception would be

throw Exception(message : String)

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

Example

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.

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

Conclusion

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