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 potentialIllegalArgumentExceptionthrown bydoSomething(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
varinstead 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?