在Java7中,我们可以同时使用try-with-resources和multi-catch吗?

在Java7中,我们可以同时使用try-with-resources和multi-catch吗?,java,java-7,Java,Java 7,大家好,我们可以在Java7中同时使用try-with-resources和multi-catch吗?我试图使用它,但它给出了编译错误。我可能用错了。请纠正我 try(GZIPInputStream gzip = new GZIPInputStream(new FileInputStream(f)); BufferedReader br = new BufferedReader(new InputStreamReader(gzip)) { br.readLine

大家好,我们可以在Java7中同时使用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();
    }

提前谢谢。

是的你可以

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

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

这在JavaSE7中是非常可能的。官方的一篇文章:

新语法允许您声明属于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.
   }
}
@马苏德在右图中说
FileNotFoundException
IOException
的一个子类,它们不能像

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

但你当然可以这样做:

try{
    //call some methods that throw IOException's
} 
catch (FileNotFoundException e){} 
catch (IOException e){}
这里有一个非常有用的Java技巧:捕获异常时,不要将网络撒得太广

希望有帮助。:)