Norbi
09/17/2021, 10:05 AMCancellationException
? Eg.:
suspend fun etc() {
try {
someOtherSuspendFun()
} catch (e: Exception) {
if (e is CancellationException) {
throw e // The operation has also failed but I should not throw WrapperException because it will interfere with the cancellation mechanism
} else {
throw WrapperException("Operation failed", e)
}
}
}
(The above is pseudo code, I have not tried it.)
Thanks.Error
instead an Exception
?streetsofboston
09/17/2021, 11:59 AMOliver.O
09/17/2021, 1:41 PMThrowable
.Norbi
09/17/2021, 2:52 PMif (e is CancellationException) ...
condition at the start of the catch block (or event a dedicated catch (e: CancellationException)
block) if it wanted to. So it must be an intentional design decision but I don't get it because it's too easy to forget to rethrow CancellationException
.ephemient
09/17/2021, 4:12 PMOliver.O
09/17/2021, 4:34 PMThe first and foremost use of exceptions in Kotlin is to handle program logic errors.
...
As a rule of thumb, you should not be catching exceptions in general Kotlin code. That’s a code smell. Exceptions should be handled by some top-level framework code of your application to alert developers of the bugs in the code and to restart your application or its affected operation. That’s the primary purpose of exceptions in Kotlin.More on the design background is presented here: https://elizarov.medium.com/kotlin-and-exceptions-8062f589d07
Norbi
09/17/2021, 5:40 PMOliver.O
09/17/2021, 6:04 PMinline fun <T, R> T.runCatchingCancellable(block: T.() -> R): Result<R> {
return try {
Result.success(block())
} catch (c: CancellationException) {
throw c
} catch (e: Throwable) {
Result.failure(e)
}
}
suspend fun etc() {
runCatchingCancellable {
someOtherSuspendFun()
}.onFailure {
throw WrapperException("Operation failed", it)
}
}