Kotlin Exception Handling
Kotlin Exception Handling
An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at
run time, that disrupts the normal flow of the program’s instructions. Exception handling is a technique,
using which we can handle errors and prevent run time crashes that can stop our program.
Kotlin Exceptions –
In Kotlin, we have only unchecked exceptions and can be caught only at run time. All the exception
classes are descendants of Throwable class.
fun main(){
var num = 10 / 0 // throws exception
println(num)
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
In the above program, we initialize the num variable with value 10/0, but we know in arithmetic divide by
zero is not allowed. While we are trying to run the program it throws an exception.
import kotlin.ArithmeticException
fun main(args : Array<String>){
try{
var num = 10 / 0
}
catch(e: ArithmeticException){
// caught and handles it
println("Divide by zero not allowed")
}
}
Output:
Divide by zero not allowed
Explanation:
In the above program, we have used try-catch block. The num variable which can throw exception is
enclosed within the braces of try block because divide by zero not defined in arithmetic. The exception
caught by the catch block and execute the println() statement.
In the above code, we have used try-catch as an expression. Declare a function test on the top of program
and it return a value using try-catch block. We have invoked the test function from main method and
passed the parameter values (10,2) The test function evaluate the arguments and return try value (10/2 =
5). But in next call, we passed (b=0) and this time exception is caught and returns expression of catch
block.
Based on the type of exceptions thrown by the code in try block, there could be multiple catch blocks
following try block.In the following Kotlin program, there is a try-catch block with multiple blocks.
import java.io.IOException
fun main() {
val a = 6
val b = 0
var c : Int
try {
c = a/b
print(c)
} catch (e : IOException){
println("An IOException occurred. Please Handle.")
} catch (e : Exception){
println("An Exception occurred. Handle.")
}
}
Run this program and observe the output.
Output
An Exception occurred. Handle.
Process finished with exit code 0
The exception thrown by the try block is ArithmeticException. In the catch section, there are two catch
blocks. The first one handles IOException, which is not a specific match. So, the control goes to the
second catch block. This catch block handles any Exception. So, the second catch block gets executed.
fun main(){
try{
var ar = arrayOf(1,2,3,4,5)
var int = ar[6]
println(int)
}
finally {
println("This block always executes")
}
}
Output:
In the above program, we have used try with finally block and skipped the catch block. Here, exception is
not handled by catch block but executes the finally block.
try {
// code that can throw exception
} catch(e: ExceptionName) {
// catch the exception and handle it.
} finally {
// finally block code
}
We can also use try, catch and finally blocks all together.
Kotlin program of using finally block with try-catch block-
Output:
java.lang.ArithmeticException: / by zero
This block always executes
Kotlin throw keyword –
In Kotlin, we use throw keyword to throw an explicit exception. It can also be used to throw a custom
exception.
Output: