Jules Olléon
Jules Olléon

Reputation: 6888

Kotlin: handling exception when defining a val

I'm working on a kotlin web backend and have something like this:

try {
    val uuid = UUID.fromString(someString)
} catch (e: IllegalArgumentException) {
    throw BadRequestException("invalid UUID")
}

doSomething(uuid)

The code above doesn't compile since uuid is unresolved outside the try block.

Alternatives I can imagine are:

This throw BadRequestException pattern is working well otherwise so I don't want to change the return type of the method or something like that in order to avoid throwing.

Is there a better / more elegant / recommended pattern for this in Kotlin?

Upvotes: 0

Views: 216

Answers (1)

Tenfour04
Tenfour04

Reputation: 93609

In Kotlin, try/catch can be used as an expression. Branches that throw don't affect the resolved type. So you can write:

val uuid = try {
    UUID.fromString(someString)
} catch (e: IllegalArgumentException) {
    throw BadRequestException("invalid UUID")
}

Upvotes: 5

Related Questions