这在 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 技巧:当捕获异常时,不要将网络撒得太宽。
希望能帮助到你。:)