Introduction
In this part, we are going to learn about Kotlin Exception Handling which plays a major role in all programming languages. Those who are new to Kotlin and are willing to learn, go through this article series starting here: for the Introduction to Kotlin.

Exception Handling
An exception is a runtime Error that can break your program. This may occur because of running out of memory space, condition like divided by zero, array out of the bond. To handle this type of Error only Exception Handling is Used.
keywords of exception handling
-
try
-
catch
-
finally
-
throw
try: try block contains set of statements to generate an exception. It is followed by either catch or finally or both of the keyword.
catch:catch block is used for catch the exception from try block.
finally:finally block always execute the code statement.
throw:throw keyword is used to throw an exception.
Kotlin Unchecked Exception
The unchecked exception is thrown due to mistakes in code. This exception type is known as the Runtime Exception class. The Unchecked exception is checked only at run time.
Following are the example of an unchecked exception,
-
ArithmeticException: when a number divide by zero.
-
ArrayIndexOutOfBoundExceptions: when an incorrect index value access with an array.
-
SecurityException: security violation thrown by the security manager.
-
NullPointerException: a method or property on a null object is invoked.

Kotlin try-catch
Kotlin try is used for exception handling. The try keyword is used to throw the exception and the catch keyword is used to handle the exception. Kotlin try is followed by either catch or finally or both of the keyword.
Syntax
- try {
- //code that throws an exception
- } catch (e: SomeException) {
- //code that handles an exception
- }
Example
- fun main(args: Array < String > ) {
- try {
- val data = 15 / 0 //throw exception
- } catch (e: ArithmeticException) {
- println(e)
- }
- println("code below exception...")
- }
Output
java.lang.ArithmeticException: / by zero
code below exception...
Kotlin try as an Expression
We can use try as an expression that returns a value. The try expression is either the last expression of try or catch.
Example of try as an Expression
- fun main(args: Array < String > ) {
- val str = getNum("20")
- println(str)
- }
- fun getNum(str: String): Int {
- return try {
- Integer.parseInt(str)
- } catch (e: ArithmeticException) {
- 0
- }
- }
Output
20
Example of catch as an Expression
- fun main(args: Array < String > ) {
- val str = getNum("21.5")
- println(str)
- }
- fun getNum(str: String): Int {
- return try {
- Integer.parseInt(str)
- } catch (e: NumberFormatException) {
- 0
- }
- }

Join the conversation! Your thoughts help the community grow.