How to Use try – catch as an Expression in Kotlin?
Last Updated :
13 Jan, 2022
The try statement consists of a try-block, which contains one or more statements. { } must always be used, even for single statements. A catch-block, a finally-block, or both must be present. This gives us three forms for the try statement:
- try…catch
- try…finally
- try…catch…finally
A catch-block contains statements that specify what to do if an exception is thrown in the try-block. If any statement within the try-block (or in a function called from within the try-block) throws an exception, control is immediately shifted to the catch-block. If no exception is thrown in the try-block, the catch-block is skipped. You can nest one or more try statements. If an inner try statement does not have a catch-block, the enclosing try statement’s catch block is used instead. The finally-block will always execute after the try-block and catch-block(s) have finished executing. It always executes, regardless of whether an exception was thrown or caught.
try – catch as an expression
Exceptions in Kotlin are both similar and different compared to those in Java. In Kotlin, throwable is the superclass of all the exceptions, and every exception has a stack trace, message, and an optional cause. The structure of try-catch is also similar to that used in Java. In Kotlin, here’s how a try-catch statement looks:
Kotlin
try {
catch (e: SomeException) {
}
finally {
}
|
At least one catch block is mandatory and the finally block is optional, and so it can be omitted. In Kotlin, try-catch is special as it enables it to be used as an expression. In this article, we will see how we can use try-catch as an expression.
Example
Let’s write a simple program that takes in a number as an input and assigns its value to a variable. If the entered value is not a number, we catch the NumberFormatException exception and assign -1 to that variable:
Kotlin
fun main (args: Array<String>) {
val str= "23"
val a: Int? = try { str. toInt () } catch (e: NumberFormatException)
{- 1 }
println (a)
}
|
Output:
23
Now, let’s try something crazy and deliberately try to throw the exception:
Kotlin
fun main (args: Array<String>){
val str= "abc"
val a: Int? = try { str. toInt () } catch (e: NumberFormatException)
{ - 1 }
printin (a)
}
|
Output:
-1
The usage of try-catch will help you a lot in edge cases as they can be used as an expression.
Explanation
The reason we can use try-catch as an expression is that both try and throw are expressions in Kotlin and hence can be assigned to a variable. When you use try-catch as an expression, the last line of the try or catch block is returned. That’s why, in the first example, we got 23 as the returned value and we got -1 in the second example.
Here, one thing to note is that the same thing doesn’t apply to the finally block – that is, writing the finally block will not affect the result:
Kotlin
fun main (args: Array<String>) {
val str= "abc"
val a: Int = try {
str.toInt ()
} catch (e: NumberFormatException) {
- 1
} finally {
- 2
}
printIn (a)
}
|
Output:
-1
As you can see, writing the finally block doesn’t change anything.
In Kotlin, all the exceptions are unchecked, which means that we don’t need to apply try-catch at all. This is quite different than Java, where if a method throws an exception, we need to surround it with try-catch. Here’s an example of an IO operation in Kotlin:
Kotlin
fun fileToString(file: File) : String {
fileContent = Files.readAllBytes (file)
return String (fileContent)
}
|
As you can see, we don’t need to wrap things with try-catch if we don’t want to. In Java, we couldn’t proceed without handling this exception.
Share your thoughts in the comments
Please Login to comment...