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: 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 {
-
- } catch (e: SomeException) {
-
- }
Example
- fun main(args: Array < String > ) {
- try {
- val data = 15 / 0
- } 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
- }
- }
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
- fun main(args: Array < String > ) {
- try {
- val a = IntArray(6)
- a[6] = 20 / 0
- } catch (e: ArithmeticException) {
- println("arithmetic exception catch")
- } catch (e: ArrayIndexOutOfBoundsException) {
- println("array index outofbounds exception")
- } catch (e: Exception) {
- println("parent exception class")
- }
- println("code after try catch...")
- }
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
- try {
-
- try {
-
- } catch (e: SomeException) {}
- } catch (e: SomeException) {}
Example
- fun main(args: Array < String > ) {
- val nume = intArrayOf(8, 8, 16, 32, 64, 128, 256, 512)
- val deno = intArrayOf(4, 0, 4, 4, 0, 8)
- try {
- for (i in nume.indices) {
- try {
- println(nume[i].toString() + " / " + deno[i] + " is " + nume[i] / deno[i])
- } catch (exc: ArithmeticException) {
- println("Can't divided by Zero!")
- }
- }
- } catch (exc: ArrayIndexOutOfBoundsException) {
- println("Element not found.")
- }
- }
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
- fun main(args: Array < String > ) {
- try {
- val data = 20 / 10
- println(data)
- } catch (e: NullPointerException) {
- println(e)
- } finally {
- println("finally block always executes")
- }
- println("below codes...")
- }
Output
2
finally block always executes
below codes...
Kotlin throw
Kotlin throw is used to throw an explicit exception and custom exception.
Syntax
Example
- fun main(args: Array < String > ) {
- validate(15)
- println("code after validation check...")
- }
- fun validate(age: Int) {
- if (age < 18) throw ArithmeticException("under age")
- else println("eligible for drive")
- }
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.