0

嗨,我们可以在 Java 7 中同时使用 try with resources 和 multi-catch 吗?我尝试使用它,它给出了编译错误。我可能用错了。请纠正我。

try(GZIPInputStream gzip = new GZIPInputStream(new FileInputStream(f));
    BufferedReader br = new BufferedReader(new InputStreamReader(gzip))
    {
         br.readLine();
    }
    catch (FileNotFoundException | IOException e) {
         e.printStackTrace();
    }

提前致谢。

4

2 回答 2

8

是的!你可以。

但是,您的问题在于FileNotFoundException. IOException因为FileNotFoundException是 的子类IOException,这是无效的。仅IOException在 catch 块中使用。您还缺少)try 语句中的一个右括号。这就是为什么,你有错误。

 try(GZIPInputStream gzip = new GZIPInputStream(new FileInputStream(f));
     BufferedReader br = new BufferedReader(new InputStreamReader(gzip)))
 {
    br.readLine();
 }
 catch (IOException e) {
    e.printStackTrace();
 }
于 2013-10-10T08:09:41.847 回答
1

这在 Java SE 7 中非常有可能。Oracle 官方文档中的一段:

新语法允许您声明属于 try 块的资源。这意味着您提前定义资源,运行时会在执行 try 块后自动关闭这些资源(如果它们尚未关闭)。

public static void main(String[] args)
{
   try (BufferedReader reader = new BufferedReader(
    new InputStreamReader(
    new URL("http://www.yoursimpledate.server/").openStream())))
   {
    String line = reader.readLine();
    SimpleDateFormat format = new SimpleDateFormat("MM/DD/YY");
    Date date = format.parse(line);
   } catch (ParseException | IOException exception) {
    // handle I/O problems.
   }
}

@Masud 说得对,它FileNotFoundException是 的子类IOException,并且它们不能像这样使用

catch (FileNotFoundException | IOException e) { e.printStackTrace(); }

但你当然可以这样做:

try{
    //call some methods that throw IOException's
} 
catch (FileNotFoundException e){} 
catch (IOException e){}

这是一个非常有用的 Java 技巧:当捕获异常时,不要将网络撒得太宽

希望能帮助到你。:)

于 2013-10-10T08:20:54.067 回答