Kotlin — Try/Catch as Expression

J Banks
Software Tidbits
Published in
2 min readJun 13, 2020
Try & Catch

In this software tidbit, we use Kotlin’s try/catch capabilities to perform a type conversion for variables representing numbers. The ability to use try/catch as an expression makes for code that is defensive and clean.

Problem

We need to convert a String value received from a file record into an Int value. For this example, the requirement is to invoke a method included with a third-party library. The API throws a checked NumberFormatException when the value supplied can’t be parsed to a number.

This exception is documented with the API, so we want to handle and provide a default value when the constant can’t be converted. A naive approach is to create a default value and if the exception occurs, log it, and move forward with the calculation.

var constantFromFile = 1try {
constantFromFile = Integer.valueOf(getConstantFromFile())
} catch (ex: NumberFormatException) {
println("Can't convert to number, defaulting to 1!")
}

val calculation = 100 * constantFromFile

This approach solves the problem, but over time could cause subtle defects that are hard to locate and test. Imagine having more lines of code added and an unintended modification is made to the constant variable’s initialized value.

var constantFromFile = 123/* Lots of other code added over time */try {
constantFromFile = Integer.valueOf(getConstantFromFile())
} catch (ex: NumberFormatException) {
println("Can't convert to number, defaulting to 1!")
}

val calculation = 100 * constantFromFile

This is where having a more direct way of handling the exception and assigning the value of the constant would be handy.

Solution

In Kotlin, a try/catch can simply be used as an expression, so instead of throwing the exception back up the chain or relying on a previously set value, handle it with a Kotlin expression and an immutable variable.

Here we detect the NumberFormatException for the provided String value and default its value to 1 if the exception occurs.

fun usingTryCatchAsExpression(inputValue: String): Number {
return try {
return invokeLibWith(inputValue)
} catch (ex: NumberFormatException) {
1
}
}

Using the try/catch as an expression allows you to maintain the conversion in one place with the side-effects of easier comprehension and easier testing.

Running

The results of the try/catch as an expression can be illustrated when invoking the usingTryCatchExpression function passing in different immutable constant values. First, a string with value “1000” followed by a string with value “abc123”.

val app = TryCatch()

val firstConstant = "1000"
val firstReturn = app.usingTryCatchAsExpression(firstConstant)
println("First Run: $firstReturn")

val secondConstant = "abc123"
val secondReturn = app.usingTryCatchAsExpression(secondConstant)
println("Second Run: $secondReturn")
Output:First Run: 1000
Second Run: 1

There you have it try/catch used as an expression with Kotlin. I hope you enjoyed this software tidbit. Checkout the shared source and don’t forget to like this if you find it useful in your Kotlin development!

Until next time …

--

--