【问题标题】:Using a Try with no catch and no finally使用没有 catch 和没有 finally 的 Try
【发布时间】:2020-08-04 22:40:56
【问题描述】:

我正在尝试从一个名为“Baeldung”的来源中获取示例,他们展示了如何使用 HttpURLConnection 执行 Json 发布请求。部分示例如下代码 sn -p ...

try(BufferedReader br = new BufferedReader(
  new InputStreamReader(con.getInputStream(), "utf-8"))) {
    StringBuilder response = new StringBuilder();
    String responseLine = null;
    while ((responseLine = br.readLine()) != null) {
        response.append(responseLine.trim());
    }
    System.out.println(response.toString());
}

这段代码使用了没有 catch 或没有 finally 的 try。我不知道这是可能的。这里发生了什么?如果抛出异常会怎样?

【问题讨论】:

    标签: try-catch httpurlconnection


    【解决方案1】:

    BufferedReader 将始终自动关闭,因为它实现了 AutoCloseable 并在 try 语句中初始化。所有异常都将传递给调用函数

    查看https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

    【讨论】:

      猜你喜欢
      • 2011-06-01
      • 2012-03-06
      • 1970-01-01
      • 2013-09-21
      • 1970-01-01
      • 2011-05-17
      • 1970-01-01
      • 2014-11-27
      • 2011-02-06
      相关资源
      最近更新 更多