剪不断,理还乱,是离愁。别是一般滋味在心头。
——李煜《相见欢》
IO异常的处理
1. JDK7前处理
我们知道Java中异常处理有两种方式,一种是throw,一种是try-catch,我们首先要知道这两种方式的使用。
throw 异常之后,后面的代码将不会执行 
try-catch时,即使catch到了异常之后,后面的代码还是会继续执行 
刚学习的时候为了方便我们经常使用throw将异常抛出,而实际开发中并不能这样处理,建议使用 try…catch…finally 代码块,处理异常部分。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
   | public class HandleException {     public static void main(String[] args) {                  FileWriter fw = null;         try {                          fw = new FileWriter("fw.txt");                          fw.write("justweb程序员");          } catch (IOException e) {             e.printStackTrace();         } finally {                          try {                 if (fw != null) {                     fw.close();                 }             } catch (IOException e) {                 e.printStackTrace();             }                      }     } }
  | 
 
2. JDK7的处理
还可以使用JDK7优化后的 try-with-resource 语句,该语句确保了每个资源在语句结束时关闭。所谓的资源(resource)是指在程序完成后,必须关闭的对象。
1 2 3 4 5 6 7 8 9 10 11
   | public class HandleException {     public static void main(String[] args) {                  try ( FileWriter fw = new FileWriter("fw.txt"); ) {                          fw.write("简维程序员");          } catch (IOException e) {             e.printStackTrace();         }     } }
  | 
 
3. JDK9的改进(了解内容)
JDK9中 try-with-resource 的改进,对于引入对象的方式,支持的更加简洁。被引入的对象,同样可以自动关闭,无需手动close,我们来了解一下格式。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
   | public class TryDemo {     public static void main(String[] args) throws IOException {                  final FileReader fr = new FileReader("in.txt");         FileWriter fw = new FileWriter("out.txt");                  try (fr; fw) {                          int b;                          while ((b = fr.read())!=‐1) {                                  fw.write(b);             }         } catch (IOException e) {             e.printStackTrace();         }     } }
  | 
 
☆