Kotlin Exception handling

An exception is a runtime problem that occurs in the program and leads to program termination. This may occur due to running out of memory space, array out of bond, and conditions like divided by zero. To handle this type of problem during program execution the technique of exception handling is used.


Exception handling is a technique that handles runtime problems and maintains the flow of program execution.

There are four different keywords used in exception handling. These are:

  • try: try block contains a set of statements white might generate an exception. It must be followed by either catch or finally or both.
  • catch: catch block is used to catch the exception thrown from the try block.
  • finally: finally block always execute whether an exception is handled or not. So it is used to execute important code statements.
  • throw: throw keyword is used to throw an exception explicitly.


Kotlin Unchecked Exception

An unchecked exception is that exception that is thrown due to mistakes in our code. This exception type extends the exceptions class. The Unchecked exception is checked at run time. Following are some examples of unchecked exceptions:

  • ArithmeticException: thrown when we divide a number by zero.
  • ArrayIndexOutOfBoundExceptions: thrown when an array has been tried to access with an incorrect index value.
  • SecurityException: thrown by the security manager to indicate a security violation.
  • NullPointerException: thrown when invoking a method or property on a null object.

Multiple catch Block:

We can use multiple catch blocks in our code. Kotlin multiple catch blocks are used when we are using different types of operation in the try block which may cause different exceptions in the try block.

    try {  
val a = IntArray(5)
a[5] = 10 / 0
} catch (e: ArithmeticException) {
println("arithmetic exception catch")
} catch (e: ArrayIndexOutOfBoundsException) {
println("array index outofbounds exception")
} catch (e: Exception) {
println("parent exception class")
}
Note:  At a time only one exception occurs and at a time only one catch block is executed.

Rule: All catch blocks must be placed from most specific to general i.e. catch for ArithmeticException must come before catch for Exception.


Nested try-catch block:

We can also able to use nested try blocks whenever required. A nested try-catch block is such a block in which one try-catch block is implemented into another try block.

The requirement of a nested try-catch block arises when a block of code generates an exception and within that block, another code statement also generates another exception.

val nume = intArrayOf(4, 8, 16, 32, 64, 128, 256, 512)  
val deno = intArrayOf(2, 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:
4 / 2 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.

finally Block:

Kotlin finally blocks such block which is always executed whether an exception is handled or not. So it is used to execute important code statements.
    try {  
val data = 10 / 5
println(data)
} catch (e: NullPointerException) {
println(e)
} finally {
println("finally block always executes")
}
Note: The finally block will not be executed if program exits (either by calling exitProcess(Int) or any error that causes the process to abort).


throw keyword:

Kotlin throw keyword is used to throw an explicit exception. It is used to throw a custom exception.
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

Comments