首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Java:拖到下一个`catch`子句

Java:拖到下一个`catch`子句
EN

Stack Overflow用户
提问于 2018-12-10 22:42:58
回答 2查看 355关注 0票数 1

我有以下结构:

代码语言:javascript
运行
复制
try {
  Request.Get(url).execute() // Apache Fluent
  // do some other stuff
} catch (HttpResponseException e) {
  if (e.getStatusCode() != 404) {
    //drop to next catch clause
  }
  handle404(e);
} catch (IOException e) {
  handleGenericIOException(e);
}

我不知道if语句中包含了什么内容。我只想说“如果异常不是404,就像这个子句从来没有捕捉到它一样”。但是简单地调用throw e就会把它从方法中抛出。有没有办法向前传递到下一个catch子句?

EN

回答 2

Stack Overflow用户

发布于 2018-12-10 22:44:41

嵌套您的异常处理程序。

代码语言:javascript
运行
复制
try {
  try {
    Request.Get(url).execute() // Apache Fluent
    // do some other stuff
  } catch (HttpResponseException e) {
    if (e.getStatusCode() != 404) {
      throw e;
    }
    handle404(e);
  }
} catch (IOException e) {
  handleGenericIOException(e);
}

因为HttpResponseExceptionIOException的子类,所以重新抛出将被捕获在外部的try / catch块中。

票数 3
EN

Stack Overflow用户

发布于 2018-12-10 22:56:41

我不认为你可以“放弃”到下一个catch子句,但你可以这样做:

代码语言:javascript
运行
复制
try {
  Request.Get(url).execute() // Apache Fluent
  // do some other stuff
} catch (IOException e) {
  if (e instanceof HttpResponseException
      && ((HttpResponseException)e).getStatusCode()== 404) {
    handle404(e);
  } else {
    handleGenericIOException(e);
  }
}

因为IOException也应该捕获HttpResponseExceptions (如果它是一个org.apache.http.client.HttpResponseException)

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53707975

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档