Reputation: 6888
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:
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)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?
Upvotes: 0
Views: 216
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