马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
[优美的Java代码之try...catch]
目录
概述
通常我们使用try...catch()捕获异常时,如果遇到类似IO流的处理,要在finally部分关闭IO流。这是JDK1.7之前的写法了;
在JDK7以后,可以使用优化后的try-with-resource语句,该语句确保了每个资源,在语句结束时关闭。所谓的资源是指在程序完成后,必须关闭的流对象。写在()里面的流对象对应的类都实现了自动关闭接口AutoCloseable。
优化
语法:- try (创建流对象语句,如果多个,使用';'隔开) {
- // 读写数据
- } catch (IOException e) {
- e.printStackTrace();
- }
复制代码 优化前写法(JDK1.7之前)
- Properties prop = new Properties();
- File configFile = new File("/home/appconfig.properties");
- FileInputStream fs = null;
- InputStreamReader reader = null;
- try {
- fs = new FileInputStream(configFile);
- reader = new InputStreamReader(fs, "utf-8");
- prop.load(reader);
- } catch (Exception e) {
- Logger.error("load file error!!", e);
- } finally {
- try {
- if (reader != null) {
- reader.close();
- }
- if (fs != null) {
- fs.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
复制代码 优化后写法(JDK1.7及以后)
- try (FileInputStream fs = new FileInputStream(configFile); InputStreamReader reader = new InputStreamReader(fs, "utf-8")) {
- prop.load(reader);
- } catch (Exception e) {
- Logger.error("load file error!!", e);
- }
复制代码 延伸阅读:嵌套的文件流如何正确的关闭
- 嵌套打开的流只需关闭最后打开的流,先打开的会自动关闭;
- 打开的流可以多次关闭不会出错;
- 后面尝试打开流时可能会发生异常,此时要考虑关闭前面已经打开的流。
|