| import java.io.*; class b2 { public static void main(String args[]) { try { String filename = "test.dat" ; FileReader fp = new FileReader(filename); for (int i = 0 ; ; ) { i = fp.read(); if ( i == -1) break; System.out.print((char)i); } } catch (IOException e) { System.out.println("例外 - " + e); } } } # javac b2.java # java b2 aaaaa bbbbb ccccc # cat test.dat aaaaa bbbbb ccccc |
| try { ……ここにエラーが起きるかも知れないという処理を書く…… } catch(Exception e) { ……ここに、エラーが起きた時にどうするかを書く…… } |
| class b21 { public static void main(String args[]) { try { String sline ; String filename = "test.dat" ; BufferedReader reader = new BufferedReader(new FileReader(filename)); while( (sline = reader.readLine()) != null ){ System.out.println(sline); } reader.close(); } catch (IOException e) { System.out.println("例外 - " + e); } } } |