Exception Handling exception exception handling trycatchfinally blocks ErrorExceptionRuntimeException
例外処理 Exception Handling • • 例外(exception)とは何か 例外処理(exception handling)とは何か メソッドの実行時基本流れ図 例外処理の基本構造 – try/catch/finally blocks Error/Exception/Runtime_Exception Throwableクラスと例外クラスの定義 例外オブジェクト:例外スロー(throws, throw)
Java言語の例外の例 (例外処理なし) Example of Java exception without exception handling 配列の範囲を超える ゼロによる割り算 public class array. Test { public class Divide. By. Zero { public static void main(String[] args) { int[ ] a = new int[3]; System. out. println( quotient(3, 5)); System. out. println("a[2]に代入する"); System. out. println( quotient(3, 0)); a[2] = 8; System. out. println( quotient(5, 6)); System. out. println("a[2]に代入した"); } System. out. println("a[3]に代入する"); public static double quotient(int bunshi, int bunbo) { a[3] = 5; System. out. println("a[3]に代入した"); return (double) bunshi / bunbo; } System. out. println("終了します"); } } } 実行結果:L 61 ここで例外 (配列の範囲を越えた) が起きる ここで例外 実行結果:L 62 (ゼロによる割り算) が起きる
Java言語の例外処理の例(Example of exception handing) public class exception. Test{ public static void main(String[] args) { int[ ] a = new int[3]; try { System. out. println(“a[2]に代入する”); a[2] = 8; (配列の範囲を越えた) System. out. println("a[2]に代入した"); がスローされる。 System. out. println(“a[3に代入する”); a[3] = 5; キャッチした例 外オブジェクトを 出力する ここで例外オブジェクト throw System. out. println("a[3]に代入した"); } catch (Array. Index. Out. Of. Bounds. Exception e) { handling System. out. println("例外" + e + "です"); } catch (Exception e) { 例外がスキップ System. out. println("Exception" + e + "です"); ここで例外オブジェクト (配列の範囲を越えた) をキャッチする。 catch } finally { System. out. println("finally"); } System. out. println("終了します"); } } 実行結果: L 61, L 62
Throwableクラスと例外クラスの定義 public class Throwable extends Object{ Object public Throwable(); public Throwable(String message); Throwable public String get. Message(); public void print. Stack. Trace(); Exception …… error … } … Runtime Exception public class Error extends Throwable{ public class Exception extends Throwable{ public Error(); public Exception(); public Error(String s); public Exception(String s); } } Other Exception – checked exception: must be caught and handled … Class. Not. Found. Exception Runtime. Exception – unchecked exception: may or may not be caught and handled …… IOException Arithmetic. Exception AWTException …… Index. Out. Of. Bounds. Exception Array. Index. Out. Of. Bounds. Exception String. Index. Out. Of. Bounds. Exception public class Divide. By. Zero. Exception extends Exception{ public Divide. By. Zero. Exception() Negative. Array. Size. Exception { super(“Attempted to divide by zero”); } …… }
Array. Index. Out. Of. Bounds. Exception Runtime 例外クラスの例 java. lang. Object | +--java. lang. Throwable | +--java. lang. Exception Array. Index. Out. Of. Bounds. Exception() Constructs an Array. Index. Out. Of. Bounds. Exception with no detail message. | Array. Index. Out. Of. Bounds. Exception(int index) +--java. lang. Runtime. Exception Constructs a new Array. Index. Out. Of. Bounds. Exception class with an argument indicating the illegal index. | +--java. lang. Index. Out. Of. Bounds. Exception | +--java. lang. Array. Index. Out. Of. Bounds. Exception try { Array. Index. Out. Of. Bounds. Exception(String s) Constructs an Array. Index. Out. Of. Bounds. Exception class with the specified detail message. public String get. Message() int a[] = new int[2]; Returns the errort message string of this throwable object. a[4] = 10; ; public void print. Stack. Trace() } catch (Array. Index. Out. Of. Bounds. Exception e) { Prints this Throwable and its backtrace to the standard error stream. System. out. println("exception: " + e. get. Message()); e. print. Stack. Trace(); }
throws節とthrow文 throws節を使って、メソッドは指定した例外(オブジェクト)をスローする(生成する) 可能性があるという宣言。 メソッドの中に、throw文で例外をスローします。 Divide. By. Zero. Exception を宣言します public class Divide. By. Zero. Exception extends Exception{ 例外は二種類: public Divide. By. Zero. Exception() checked – 自分定義の例外クラス { super(“Attempted to divide by zero”); } コンストラクタ } public double quotient(int numerator, int denominator) throws Divide. By. Zero. Exception { if (denominator == 0) unchecked – ErrorとRuntime. Exceptionのsub クラス unchecked exception クラスは、メソッドに throws節でこの例外をスローする可能性があ るという宣言することが必要ない。 checked exception クラスは、メソッドにthrows 節でこの例外をスローする可能性があるとい う宣言することが必要です。 このメソッドには throw new Divide. By. Zero. Exception(); Divide. By. Zero. Exceptionをス return (double) numerator / denominator; ローする可能性があるという 宣言 } Divide. By. Zero. Exceptionを ここでスローします
例外のキャーチと処理 (Example of exception handling) public class Divide. By. Zero { public static void main(String[] args) { try { System. out. println( quotient(3, 5)); 実行結果: L 65 メソッド quotient()を呼 び出し System. out. println( quotient(3, 0)); System. out. println( quotient(5, 6)); } ここでキャッチ される このメソッドは catch (Divide. By. Zero. Exception e) { System. out. println( e); } キャッチした例外オ ブジェクトを出力する Divide. By. Zero. Exceptionをス finallyブロック なくでもよい ローする可能性があるという 宣言 finally{System. out. println( “Finished !”); } } public double quotient(int numerator, int denominator) Divide. By. Zero. Exceptionを throws Divide. By. Zero. Exception { if (denominator == 0) throw new Divide. By. Zero. Exception(); return (double) numerator / denominator; } } Divide. By. Zero. Exception ここでスローします を宣言します public class Divide. By. Zero. Exception extends Exception{ public Divide. By. Zero. Exception() { super(“Attempted to divide by zero”); } }
課題 (Exercise) 1 y = f(x) = 1/log(2 x²-5 x+2) for x=0~9を計算して、y[10] の配列の中に結果を格納するアプレットのプログラ ム(example)が左に与えられている。プログラムとそ れに連なったHTMLファイルをタイプした後、コ ンパイルして実行せよ。テキストフィールドに 0~ 9 の数字を入力し、アプレットに何が表示されるのか を確認せよ。0未満、もしくは 9以上の数字を入力し たとき、MS-DOSウィンドウにどのような例外 メッセージが表示されるか?例外が起こったとき、 Array. Index. Out. Of. Bounds. Exceptionをtry/catchブロック を使ってメッセージ “You must enter an integer from 0 to 9”が表示されるようにせよ。 2 整数以外の文字を入力したとき、どのような例外メ ッセージがMS-DOSウィンドウ上に表れるか? 例外が起こったとき、try/catchブロックを使用して Number. Format. Exception をハンドルし、“You must enter an integer. Other characters are illegal”というメッ セージを表示させよ。 3 "1"を入力したとき、特殊文字が表示される。これは log()関数の変数が負の値であるためである。レクチ ャーノートのDivide. By. Zero. Exceptionクラスを 参照して、このタイプの例外と一致する例外クラス log. Of. Negative. Valueを定義せよ。またメソッド(int x){. . . }で例外をスローせよ。前述のプログラムの例 外をハンドルせよ、またそれに対応する例外メッ セージ "Unable to calculte the logarithm for a negative value"を示せ。 import java. applet. Applet; import java. awt. *; import java. awt. event. *; import java. text. Decimal. Format; public class example extends Applet implements Action. Listener { private Label p 1; private Text. Field input; private int x; private double y[] = new double[10]; public void init() { p 1=new Label("Enter a number (0 to 9)"); add(p 1); input = new Text. Field(10); input. add. Action. Listener(this); add(input); } public void paint(Graphics g) { Decimal. Format precision 2 = new Decimal. Format("#. 00"); int xx= 70; g. draw. String("y[0~9]: ", 20, 50); for(int i=0; i<y. length; i++) { g. draw. String(precision 2. format(y[i])+" ", xx, 50); xx+=30; } } public void action. Performed(Action. Event e) { Decimal. Format precision 2 = new Decimal. Format("#. 00"); x = Integer. parse. Int(input. get. Text()); y[x]= f(x); show. Status("y["+x+"] = f("+x+")="+ precision 2. format(y[x])); input. set. Text(""); repaint(); } public static double f(int x) { return 1. 0/(double)(Math. log(2*x*x-5*x+2)); } } <html> <applet code="example. class" width=450 height=100> </applet> </html>
Exercise 1 Give the left applet program that calculates y = f(x) = 1/log(2 x²-5 x+2) for x=0~9, and puts the results into an array y[10]. Type the program and the associative HTML file, compile and run it. Input number 0 ~9 in the text filed and watch what will be shown in the applet. When you input a number less than 0 or greater than 9, what exception messages are displayed in your MS-DOS window? Handle this Array. Index. Out. Of. Bounds. Exception using try/catch blocks and show a message, “You must enter an integer from 0 to 9”, when the exception occurs. 2 When you input a character(s) which is not an integer, what exception messages are displayed in your MSDOS window? Handle this Number. Format. Exception using try/catch blocks and show a message, “You must enter an integer. Other characters are illegal”, when the exception occurs. 3 When you input ‘ 1’, a special symbol will be shown. This is because the variable of the log( ) function is a negative value. Define an exception class corresponding to this type of exception by referring the Divide. By. Zero. Exception class in the lecture note, and throw the exception in the method f(int x) { … }. Handle the exception in the previous program, and show the corresponding exception message. import java. applet. Applet; import java. awt. *; import java. awt. event. *; import java. text. Decimal. Format; public class example extends Applet implements Action. Listener { private Label p 1; private Text. Field input; private int x; private double y[] = new double[10]; public void init() { p 1=new Label("Enter a number (0 to 9)"); add(p 1); input = new Text. Field(10); input. add. Action. Listener(this); add(input); } public void paint(Graphics g) { Decimal. Format precision 2 = new Decimal. Format("#. 00"); int xx= 70; g. draw. String("y[0~9]: ", 20, 50); for(int i=0; i<y. length; i++) { g. draw. String(precision 2. format(y[i])+" ", xx, 50); xx+=30; } } public void action. Performed(Action. Event e) { Decimal. Format precision 2 = new Decimal. Format("#. 00"); x = Integer. parse. Int(input. get. Text()); y[x]= f(x); show. Status("y["+x+"] = f("+x+")="+ precision 2. format(y[x])); input. set. Text(""); repaint(); } public static double f(int x) { return 1. 0/(double)(Math. log(2*x*x-5*x+2)); } } <html> <applet code="example. class" width=450 height=100> </applet> </html>
課題 • Define your own array. Index. Out. Of. Bound. Exception. Make a Java applet to input 10 integers from Text. Field, store the integers in an array with considerations of handling exception using your own defined array. Index. Out. Of. Bound. Exception. ex 1 • Define your own divide. By. Zero. Exception (modify the example in today’s lecture note so that a denominator has a float type rather than integer type ). Make a Java applet that is able to input two numbers with float or integer type from two Text. Field, and do calculation of division (refer to the textbook fig. 12. 1). ex 2
- Slides: 15