例外処理と ファイル入出力 情報システム学科 平塚聖敏
例外処理とは プログラムの実行中に発生した問題を通知するために 実行時に生成される 例外の例 オブジェクト スタックオーバーフロー メモリ不足 配列の要素数を超えて参照しようとしたりする
例外処理の手順その 1 基本の例外処理 1. try ブロックで処理を囲む try{ // 処理 2. catch ブロックで例外を捕捉 catch ( 例外オブジェクトパラメータ ) { // 処理 3. finally ブロックで後処理 finally { // 処理
例外処理の手順その 1 の中身 1. try ブロックで例外が起こった場合 2. ブロック内の残りの処理をスキップ 3. catchブロックの例外を探索 4. 見つかれば その処理を行う 5. 無ければfinallyブロックに進む
try ブロックには try ブロックを書いたら 必ず catch ブロックまたは finally ブロックを書かなければならない catch ブロックの後に finally ブロックを書かなくても デフォルトの finally ブロックが生成され 実行される
例外オブジェクト 例外に指定できるオブジェクトは Throwable でなければならない Throwable は すべての例外クラスのスーパークラス
Error クラス Exception クラス Error クラス 通常のアプリケーションであればキャッチすべきでない重大な問題を指す Exception クラス 通常のアプリケーションでキャッチされる可能性のある状態を指す
例外処理の例前半 class Divider { public static void main( String args[] ) { try { System.out.println("Before Division"); int i = Integer.parseInt(args[0]); int j = Integer.parseInt(args[1]); System.out.println(i/j); System.out.println("After Division");
例外処理の例後半 catch (ArithmeticException e) { Sytem.out.println("ArithmeticException"); catch (ArrayIndexOutOfBoundsException e) { System.out.pritln ("ArrayIndexOutOfBoundsException"); catch (NumberFormatException e) { System.out.println("NumberFormatException"); finally { System.out.println("finally brock");
例外処理の例 2 前半 class ClassCast { public static void main(string args[]) { try { Object obj = new Integer("85"); Double dobj = (Double)obj; // ここで java.lang.classcastexception: //java.lang.integer の例外発生!! System.out.println("After cast"); catch (Exception e) { System.out.println(e);
Exception catch ブロックの最初の例外で Exception これは全ての例外クラスに該当 従って そのほかの例外を捕捉できない
Throw ステートメント 新しいオブジェクトを作成して投げる throw new ExceptionType(args); ExceptionType は例外オブジェクトの型 args はコンストラクタの引数リストで省略可能
Throw ステートメントの例 class ThrowDemo2 { public static void main(string args[]) { try { System.out.println("before a"); a(); System.out.println("after a"); catch (Exception e){ System.out.println("main : " + e); finally { System.out.println("main : finally "); 前半
Throw ステートメントの例 後半 public static void a() { try { System.out.println("before throw statement"); throw new ArithmeticException(); catch (Exception e) { System.out.println("a : " + e); finally { System.out.println("a : finally");
Throws ステートメント 書く理由 利点 呼び出し元に対して例外を投げる可能性があるメソッドを書いた場合 どの例外が投げられるのかを明示しておくと便利 それらの例外に対処することができる ほかのプログラマが書いたコード どの例外が投げられるか分かる この Java 言語の機能を利用すれば エラーの起こりにくいプログラムを作成できる
throws の例前半 public class ThrowsDemo { public static void main(string[] args) { try { getratio(args); catch(exception e){ System.out.println(e); finally{ System.out.println("main : finally");
throws の例後半その 1 public static void getratio(string str[]) throws ArithmeticException, ArrayIndexOutOfBoundsException, NumberFormatException{ try{ double r = Double.parseDouble(str[0]); double f = Double.parseDouble(str[1]); if ( f==0.0) { throw new ArithmeticException(); System.out.println(" 比は " + r/f + " です ");
throws の例後半その 2 catch(arithmeticexception e){ System.out.println("getRatio : ArithmeticException" + e); throw new ArithmeticException(); catch(arrayindexoutofboundsexception e){ System.out.println("getRatio : " + e); throw new ArrayIndexOutOfBoundsException(); catch(numberformatexception e){ System.out.println("getRatio :" + e); throw new NumberFormatException(); finally { System.out.println("getRatio : finally");
ファイル入出力 ファイルとディレクトリ File クラスは ファイルとディレクトリのプロパティに関する情報をカプセル化したクラス プロパティには 読み取り 書き込み 前回の修正時刻 長さが含まれる ディレクトリに収めるファイルを指定できる 新しいディレクトリを作成したり 既存のファイル ディレクトリを削除 名前変更ができる
File コンストラクタ File(String path) ファイルまたはディレクトリのパスを指定 File(String directorypath, Stringn filename) ディレクトリパスとディレクトリ内のファイル名 File(File directory, String filename) ディレクトリのファイルオブジェクトとディレクトリ内のファイル名 path または filename が null の場合 NullPointerException を投げる
File クラスの例 import java.io.*; public class FileDemo { public static void main(string[] args) { try { System.out.println("pathSeparatorChar = " +File.pathSeparatorChar); System.out.println("separatorChar = " +File.separatorChar); File file = new File(args[0]); System.out.println("getName()= " +file.getname()); System.out.println("getParent() = " +file.getparent()); System.out.println("getAbsolutePath() = " + file.getabsolutepath()); System.out.println("canRead() = " +file.canread()); catch (Exception e){ e.printstacktrace();
ストリーム ストリームとは データのソースまたはデスティネーションの抽象的な概念 ストリームにより 同じテクニックで各種の物理デバイスに接続できる 1 つの入力ストリームで キーボード ファイル メモリバッファなど異なるデバイスからそのデータを読み取ることができる また出力ストリームで モニタ ファイル メモリバッファと異なったデバイスにデータを書き込める
文字ストリーム 文字ストリームとバイトストリームの2タイプ バイトストリーム バイナリデータの読み書き 文字ストリーム 文字および文字列の読み書き 入力文字ストリーム : バイトを文字に変換 出力ストリーム : 文字をバイトに変換する Javaは 内部で文字を16ビットのUnicodeで表す
クラスの階層 Object--+---Reader--+----BufferedReader +----InputStreamReader- ---FileReader +------Writer--+----BufferedWriter +---OutputStreamWriter----FileWriter +---PrintWriter
Writer クラス Write オブジェクトに基づいて同期化を行う抽象クラス OutputStreamWriter クラス Writer クラスを拡張したクラス FileWriter クラス OutputStreamWriter クラスを拡張したクラス
Witer クラスのメソッド 全てのメソッドが IOException を投げる abstract void close() throws IOException abstract void flush() throws IOException void write(int c) throws IOException void write(char buffer[]) throws IOException abstract void write(char buffer[], int index, int size) throws IOException void write(string s) throws IOException void write(string s, index, int size) throws IOException
Reader クラス 全ての文字入力ストリームに利用できる機能が定義されている抽象クラス InputStreamReader クラス Reader クラスを拡張したクラス FileReader InputStreamReader クラスを拡張したクラス
ファイルに文字を書き込む例 import java.io.*; public class FileWriterDemo { public static void main(string[] args) { try { FileWriter fw = new FileWriter(args[0]); for(int i = 0; i<12; i++){ fw.write("line " + i + " n"); fw.close(); catch (Exception e){ System.out.println("Exception : "+ e);
ファイルに文字を読み込む例 import java.io.*; public class FileReaderDemo { public static void main(string[] args) { try { FileReader fr = new FileReader(args[0]); int i; while( (i=fr.read())!= -1){ System.out.print((char)i); fr.close(); catch(exception e){ System.out.println("Exception :" + e);
バッファ付き文字ストリーム バッファ付き文字ストリームを用いると 物理デバイスへの読み書きの回数が減らせる クラス BufferedWriter BufferedReader
BufferedWriter Witer クラスの全てのメソッドを実装 改行文字の出力するメソッド newline() throws IOException
BufferedReader Reader クラスの全てのメソッドを実装 改行文字までを読み込むメソッド readline() throws IOException
BufferedWriter の例 import java.io.*; public class BufferedWriterDemo { public static void main(string[] args) { try { FileWriter fw = new FileWriter(args[0]); BufferedWriter bw = new BufferedWriter(fw); for(int i = 0; i<12; i++){ bw.write("line "+ i + " n"); bw.close(); catch(exception e){ System.out.println("Exception" + e);
BufferedReader の例 import java.io.*; public class BufferedReaderDemo { public static void main(string[] args) { try { FileReader fr = new FileReader(args[0]); BufferedReader br = new BufferedReader(fr); String s; while( (s=br.readline())!= null){ System.out.println(s); fr.close(); catch(exception e){ System.out.println("Exception :" + e);
標準入力 import java.io.*; // 無限ループのプログラム public class ReadConsole { public static void main(string[] args) { try { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); String s; while( (s=br.readline())!= null) { System.out.println(s.length()); isr.close(); catch(exception e){ System.out.println("Exception : " + e);
PrintWriter クラス Writer クラスを拡張したクラス int, float, char などの基本データ型およびオブジェクトと等価な文字列を表示する
PrintWriter クラスの例 import java.io.*; public class PrintWriterDemo { public static void main(string[] args) { try { PrintWriter pw = new PrintWriter("abc.txt"); pw.println(true); pw.println('a'); pw.println(23.45); pw.println("hello"); pw.close(); catch(exception e){ System.out.println("Exception : " + e);
例外処理の問題 ユーザーがキーボードからデータを入力し 入力されたデータの平均値を求めるプログラムを作成したい 用意するデータは double 型で 配列要素数は 5 個 捕捉する例外はつぎの 3 つとする ArithmeticException 入力データなしのとき IndexOutOfBoundsException データ数が合わないとき NumberFormatException 入力データが不正なとき
入出力 ユーザーが 999 の数を入力するまで 入力を求め ファイルに入力されたデータを書き込むプログラムを作成したい 書き込むファイル名を指定する データ入力を求める 999 でなければ さらに入力を求める 入力が終わったらデータをファイルに出力する 不正な入力の時は 例外処理をする