例外処理 と
ファイル入出力
情報システム学科
平塚 聖敏
例外処理とは
プログラムの実行中に発生した問題を通知す
るために、実行時に生成される
オブジェクト
例外の例
スタックオーバーフロー、メモリ不足
配列の要素数を超えて参照しようとしたりする
例外処理の手順 その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は例外オブジェクトの型
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の場合、
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 | +---PrintWriterWriterクラス
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)
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クラスの全てのメソッドを実装
改行文字の出力するメソッド
BufferedReader
Readerクラスの全てのメソッドを実装
改行文字までを読み込むメソッド
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); } } }