0

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:

  • move doSomething(uuid) inside the try block, but I'd rather avoid that so I don't accidentally catch some other potential IllegalArgumentException thrown by doSomething (if that happens for whatever reason I want things to fail and get a 500 in my logs so I can investigate)
  • use a nullable var instead and initialize it to null but that seems a bit ugly?

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?

0

1 Answer 1

5

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")
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.