英文:
Multiple catch blocks fail in throwing method
问题
目前,我有以下方法
另一个方法简化为以下内容:
suspend fun <T> handleRequest(
requestCaller: suspend() -> Response<T>
): Result<Something, T> {
return try {
requestCaller.invoke()
} catch(ioException: IOException) {
} catch(exception: Exception) {
}
}
当我调用上述方法并且 requestCaller.invoke()
抛出 IllegalStateException
异常时,根本没有捕获异常。
然而,当我移除第一个捕获 IOException
的 catch 块时,它正常工作。
我做错了什么吗?
英文:
Currently, I have the following method
And another method simplified to the following:
suspend fun <T> handleRequest(
requestCaller: suspend() -> Response<T>
): Result<Something, T> {
return try {
requestCaller.invoke()
} catch(ioException: IOException) {
} catch(exception: Exception) {
}
}
When I call the above method and requestCaller.invoke()
and throw IllegalStateException
, the exception is NOT caught at all.
However, when I remove the first catch block that catches IOException
, it works.
Am I doing something wrong?
答案1
得分: 4
抛出异常是拦截器中的错误操作,除非是 IOException。在Java(具有已检查异常)中强制执行此规则,但在Kotlin(无已检查异常)中不执行。
如果抛出 IOException,它会传播回调用站点。如果抛出任何其他异常类型,您的调用将被取消,并且异常将传递到当前线程的未捕获异常处理程序。
英文:
It is an error to throw an exception in an interceptor, unless it is an IOException. This is enforced in Java (which has checked exceptions) but not Kotlin (no checked exceptions).
If you throw an IOException, it’ll propagate back to your callsite. If you throw any other exception type your call will be canceled and your exception will be delivered to the current thread’s uncaught exception handler.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论