多个 catch 块在抛出方法中失效。

huangapple go评论67阅读模式
英文:

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 &lt;T&gt; handleRequest(
  requestCaller: suspend() -&gt; Response&lt;T&gt;
): Result&lt;Something, T&gt; {
  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.

huangapple
  • 本文由 发表于 2020年9月30日 09:00:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/64129551.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定