Kotlin try & catch
In this tutorial we will learn about try
and catch
block in Kotlin and how we use them to handle code which may lead to exception/error when we run it. The try
and catch
block are used to handle an exception. The code which may throw an exception is placed inside the try
block and the exception thrown by try
block is caught using catch
block.
Let's see the syntax for using the try
and catch
block in Kotlin.
Kotlin try
& catch
block
The syntax of try-catch
block is:
try {
// The code which may throw an error
}catch (e: SomeException){
// Handling the exception
}
In the syntax above, the SomeException is the name of the exception class. You can provide the name of the parent class to catch multiple child class exception classes in a single catch block or provide the name of some specific exception class to handle a single exception.
Kotlin try
& catch
- Example
Let us first see a program which will throw an exception and what will happen if we don't handle it:
fun main() {
val a: Int = 101
val b: Int = 0
println("Division of $a and $b is: ${a/b}")
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Try_catchKt.main(try-catch.kt:4)
at Try_catchKt.main(try-catch.kt)
Here we get ArithmeticException
as we tried to divide a number by zero.
Let us handle this exception using the try
and catch
block:
fun main() {
val a: Int = 101
val b: Int = 0
try {
println("Division of $a and $b is: ${a/b}")
}catch (exception: ArithmeticException){
println("Exception is handled....")
println("$a and $b cannot be divided!!")
}
}
Exception is handled....
101 and 0 cannot be divided!!
In the above code, we have specifically mentioned in our catch
block to catch the ArithmeticException
. If our code has more logic and some other statement leads to some exception which is not of ArithmeticException
type then our program will again stop exceuting abruptly with the exception message.
So we must find the right exception class to catch.
Kotlin try
& catch
Expression
The unique feature of Kotlin try-catch
block is that it can be used as an expression. It means it will return a value. The last statements of the try
and catch
block is considered as return value.
Let us write a program in which we will divide two numbers and assign the result to res
variable. If any exception occurs, we will assign -1
to res
:
fun main() {
val a: Int = 100
val b: Int = 10
val res: Int = try {
a/b
}catch (exception: ArithmeticException){
-1
}
println("The result is: $res")
}
The result is: 10
Now change the value of b
to 0
, the output will be:
The result is: -1
Summary
In this tutorial we learned about simple try-
catch
block in Kotlin and how to use them. In the next tutorial we will learn how we can use multiple catch
blocks, handling exceptions differently based on exception type.