Kotlin - Exception Handling

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.
 
Kotlin - Exception Handling
 

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 - Exception Handling
 

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
  1. try {  
  2.     //code that throws an exception    
  3. catch (e: SomeException) {  
  4.     //code that handles an exception    
  5. }  
Example
  1. fun main(args: Array < String > ) {  
  2.     try {  
  3.         val data = 15 / 0 //throw exception    
  4.     } catch (e: ArithmeticException) {  
  5.         println(e)  
  6.     }  
  7.     println("code below exception...")  
  8. }  
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
  1. fun main(args: Array < String > ) {  
  2.     val str = getNum("20")  
  3.     println(str)  
  4. }  
  5. fun getNum(str: String): Int {  
  6.     return try {  
  7.         Integer.parseInt(str)  
  8.     } catch (e: ArithmeticException) {  
  9.         0  
  10.     }  
  11. }  

Output

20
 
Example of catch as an Expression
  1. fun main(args: Array < String > ) {  
  2.     val str = getNum("21.5")  
  3.     println(str)  
  4. }  
  5. fun getNum(str: String): Int {  
  6.     return try {  
  7.         Integer.parseInt(str)  
  8.     } catch (e: NumberFormatException) {  
  9.         0  
  10.     }  
  11. }  

Output

0
 

Kotlin Multiple catch Block

 
We can use multiple catch blocks in Kotlin. Kotlin multiple catch blocks are used when we use different types of operations in try to get different exceptions.
 
Example
  1. fun main(args: Array < String > ) {  
  2.     try {  
  3.         val a = IntArray(6)  
  4.         a[6] = 20 / 0  
  5.     } catch (e: ArithmeticException) {  
  6.         println("arithmetic exception catch")  
  7.     } catch (e: ArrayIndexOutOfBoundsException) {  
  8.         println("array index outofbounds exception")  
  9.     } catch (e: Exception) {  
  10.         println("parent exception class")  
  11.     }  
  12.     println("code after try catch...")  
  13. }  

Output

arithmetic exception catch
code after try catch...
 

Kotlin Nested try-catch

 
Nested try-catch is one try-catch that is implemented into another try.
 
Nested try-catch creates a block of code which generates an exception and within that another code statement also generates another exception.
 
Syntax
  1. try {  
  2.     // code block    
  3.     try {  
  4.         // code block    
  5.     } catch (e: SomeException) {}  
  6. catch (e: SomeException) {}  

Example

  1. fun main(args: Array < String > ) {  
  2.     val nume = intArrayOf(8, 8, 16, 32, 64, 128, 256, 512)  
  3.     val deno = intArrayOf(4, 0, 4, 4, 0, 8)  
  4.     try {  
  5.         for (i in nume.indices) {  
  6.             try {  
  7.                 println(nume[i].toString() + " / " + deno[i] + " is " + nume[i] / deno[i])  
  8.             } catch (exc: ArithmeticException) {  
  9.                 println("Can't divided by Zero!")  
  10.             }  
  11.         }  
  12.     } catch (exc: ArrayIndexOutOfBoundsException) {  
  13.         println("Element not found.")  
  14.     }  
  15. }  

Output

8/ 4 is 2
Can't divided by Zero!
16 / 4 is 4
32 / 4 is 8
Can't divided by Zero!
128 / 8 is 16
Element not found.

 
Kotlin finally

 
Kotlin finally is always executed whether an exception is handled or not. It is used to execute an important code statement.
 
Example
  1. fun main(args: Array < String > ) {  
  2.     try {  
  3.         val data = 20 / 10  
  4.         println(data)  
  5.     } catch (e: NullPointerException) {  
  6.         println(e)  
  7.     } finally {  
  8.         println("finally block always executes")  
  9.     }  
  10.     println("below codes...")  
  11. }  

Output

2
finally block always executes
below codes...
 

Kotlin throw

 
Kotlin throw is used to throw an explicit exception and custom exception.
 
Syntax
  1. throw SomeException()  

Example

  1. fun main(args: Array < String > ) {  
  2.     validate(15)  
  3.     println("code after validation check...")  
  4. }  
  5. fun validate(age: Int) {  
  6.     if (age < 18) throw ArithmeticException("under age")  
  7.     else println("eligible for drive")  
  8. }  

Output

Exception in thread "main" java.lang.ArithmeticException: under age
 

Conclusion

 
In this article, we saw how to handle exceptions in Kotlin. In the next part, we will learn about null safety.
 
Next in this series: Kotlin Null Safety 


Similar Articles