第十章例外處理 - dns2.asia.edu.twdns2.asia.edu.tw/~wzyang/slides/Java/Chen/SE7ch10.pdf ·...
Transcript of 第十章例外處理 - dns2.asia.edu.twdns2.asia.edu.tw/~wzyang/slides/Java/Chen/SE7ch10.pdf ·...
-
Java
10.1
10.2
10.5 throws
10.3
10.6
10.7
10.4
10.8
10.9
-
3
(1)
(2)
(3)
(Run Time Error)
10.1
4
10.1
-
5
JDK 7.0Java
10.1
6
000
y/(100-x)xx1000
10.1
-
7
AA
10.1
8
JavaJava
500Java
10.1
-
9
(Error)
(Exception)
(Exception)(Error)Java
10.1
10
10-1010-1ch10_01.javamyJava\ch10\ch10_01.java
10.1
12345678910111213141516
/* :ch10_01.java : */
package myJava.ch10;import java.lang.*;import java.io.Console;
public class ch10_01 //{
public static void main(String args[]){
fraction obj= new fraction();obj.set_value();obj.print_value();
} }
-
11
10.1
17181920212223242526272829303132333435
class fraction{
public fraction(){ console=System.console(); }private Console console;private int numerator; //private int denominator; //public void set_value(){
System.out.print(":");numerator=Integer.parseInt(console.readLine()); System.out.print(":");denominator=Integer.parseInt(console.readLine());
}public void print_value(){
System.out.print(numerator + "/" + denominator + "=");System.out.println(numerator/denominator);
}}
12
(1)84Java
C:\>java myJava.ch10.ch10_01:8:4 8/4=2
C:\>java myJava.ch10.ch10_01:2:02/0=Exception in thread "main" java.lang.ArithmeticException: / by zero
at myJava.ch10.fraction.print_value(ch10_01.java:33)at myJava.ch10.ch10_01.main(ch10_01.java:13)
10.1
-
13
(2)203320
10-1if0
if-elseif-elseJava
10-1Java
2/0=Exception in thread
10.1
14
Java
Java
(1)Java
(2)
10.2
-
15
Javajava.lang.Throwable
java.lang.Exception
java.lang.Error
java.lang.ErrorJVMError
10.2.1 Java
16
java.lang.Exception
10-1java.lang.ArithmeticException0
NegativeArraySizeException
10.2.1 Java
-
17
Java
B-1B.8BufferedReaderreadLine(throw) IOException
readLinepublic String readLine() throws IOExceptionReads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed. Returns:A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached Throws: IOException - If an I/O error occurs
10.2.1 Java
18
IOExceptionIO
IOExceptionjava.lang.Exception
10.2.1 Java
-
19
java.lang.RuntimeException
10.2.1 Java
java.lang.Exception java.lang.ClassNotFoundException
java.lang.CloneNotSupportedException Objectclone()CloneableJavacloneCloneable
java.lang.IllegalAccessException
java.lang.InstantiationException newInstance()
java.lang.InterruptedException
java.lang.NoSuchFieldException
java.lang.NoSuchMethodException
java.lang.RuntimeException JVM
20
java.lang.RuntimeException java.lang.ArithmeticException 0java.lang.ArrayStoreException
java.lang.ClassCastException java.lang.EnumConstantNotPresentException java.lang.IllegalArgumentExceptionjava.lang.IllegalThreadStateExceptionjava.lang.NumberFormatException
java.lang.IllegalMonitorStateException java.lang.IllegalStateException
java.lang.IndexOutOfBoundsExceptionjava.lang.ArrayIndexOutOfBoundsExceptionjava.lang.StringIndexOutOfBoundsException
charAt
java.lang.NegativeArraySizeException 0java.lang.NullPointerException
nulljava.lang.SecurityException Java
java.lang.TypeNotPresentException java.lang.UnsupportedOperationException
10.2.1 Java
-
21
JavaJavaJava
Throwable
ExceptionThrowable
10.2.2
class extends Exception{
public () //{
super(); ////
}//
}
22
throw
Java
10-2
10-2ch10_02.javamyJava\ch10\ch10_02.java
10.3
-
23
1234567891011121314
/* :ch10_02.java : */
package myJava.ch10;import java.lang.*;
public class ch10_02 //{
public static void main(String args[]){
System.out.println("");int ary[] = new int[-2];System.out.println("");
} }
C:\>java myJava.ch10.ch10_02Exception in thread "main" java.lang.NegativeArraySizeException
at myJava.ch10.ch10_02.main(ch10_02.java:11)
10.3
24
11NegativeArraySizeException12
throwthrow
10.3
-
25
10-3throw10-3ch10_03.javamyJava\ch10\ch10_03.java
1234567891011121314151617
/* :ch10_03.java :throw */
package myJava.ch10;import java.lang.*;
public class ch10_03 //{
public static void main(String args[]){
System.out.println("");int i=-2;if(ijava myJava.ch10.ch10_03Exception in thread "main" java.lang.NegativeArraySizeException
at myJava.ch10.ch10_03.main(ch10_03.java:13)
10.3
-
27
10-4throw
10-4ch10_04.javamyJava\ch10\ch10_04.java
1234567891011121314151617
/* :ch10_04.java :throw */
package myJava.ch10;import java.lang.*;
public class ch10_04 //{
public static void main(String args[]) throws CmyException{
System.out.println("");int i=-2;if(ijava myJava.ch10.ch10_04Exception in thread "main" myJava.ch10.CmyException:
at myJava.ch10.ch10_04.main(ch10_04.java:13)
181920212223242526272829
class CmyException extends Exception{
public CmyException() //{
super();}public CmyException(String msg) //{
super(msg);}
}
10.3
-
29
(1)main()throws CmyException
(2)
(3)14~15
Coding
GUI
Coding
GUI
10.3
30
Javatrythrowcatchfinally
throw
trycatch[finally]
finally
10.4
-
31
trycatch[finally] try
{//
}catch(1 |2| ){
//}catch(3 | ){
//}.......catch............finally{
//}//
|
10.4
32
(1)trythrow(2)catchcatch(3)catchcatchcatch|orJDK7.0Multi-catchcatch(1 |2 )|
10.4
-
33
(4)finally
(5)trycatch[finally]trycatchJavacatchcatchJava
(6)catch
(7)trycatch[finally]
(8)10-1
10.4
34
10.4
10-1
-
35
10-56~486
10-5ch10_05.javamyJava\ch10\ch10_05.java
12345678
/* :ch10_05.java :Multi-catch */
package myJava.ch10;import java.lang.*;import java.io.Console;
public class ch10_05 //{
10.4
36
10.49101112131415161718192021222324252627282930313233343536
public static void main(String args[]){
Console console=System.console();System.out.print(":");int lottoSize=0;
try{ lottoSize=Integer.parseInt(console.readLine()); if(lottoSize>48)
throw new CmyException1(":"); else if(lottoSize
-
37
10.4
3738394041424344454647484950515253545556575859606162
class CmyException1 extends Exception{
public CmyException1() //{
super();}public CmyException1(String msg) //{
super();System.out.println(msg);
} }
class CmyException2 extends Exception{
public CmyException2() //{
super();}public CmyException2(String msg) //{
super();System.out.println(msg);
} }
38
:99
:99::66
10.4
:r0Exception in thread "main" java.lang.NumberFormatException: For input string: "r"
at java.lang.NumberFormatException.forInputString(Unknown Source)at java.lang.Integer.parseInt(Unknown Source)at java.lang.Integer.parseInt(Unknown Source)at myJava.ch10.ch10_05.main(ch10_05.java:17)
:5::66
-
39
(1)6~48
(2)38~626~48
(3)15~31trycatch[finally]1718~21lottoSizetrythrowthrow
(4)catchtryfinallytrycatch[finally]
10.4
40
(5)184819throw23~27catchfinallytrycatch[finally](6)20621throw23~27catchfinallytrycatch[finally](7)17throwcatchfinally0(8)10-7
10.4
-
41
(9)23~27Multi-catchcatchCmyException1CmyException2JDK6
10.4
2324252627:::::
catch(CmyException1 e){ System.out.println(":6");lottoSize=6;
}catch(CmyException2 e){ System.out.println(":6");lottoSize=6;
}
42
10.4
10110523~27(9)
10110523~27(9)
10210551classCmyException2extendsCmyException1
10210551classCmyException2extendsCmyException1
-
43
Multi-catchMulti-catchcatch(|)
10-2CmyException2CmyException1catch(|)
10.4
44
10-6Multi-catch
10-6ch10_06.javamyJava\ch10\ch10_06.java
10.4
1234567
/* :ch10_06.java : Multi-catch */
package myJava.ch10;import java.lang.*;
public class ch10_06 //{
-
45
10.4
89101112131415161718192021222324252627282930313233
public static void main(String args[]){
int lottoSize=99;
try{ if(lottoSize>48)
throw new CmyException1(); else if(lottoSize
-
47
10.4
52535455565758596061626364656667
class CmyException2 extends Exception{
public CmyException2() //{
super();}public void showMessage(){
System.out.println(":");}public int changeSize(){
System.out.println(":6");return 6;
}}
48
10.4
C:\myJava\ch10>javac ch10_06.javach10_06.java:21: error: cannot find symbol
e.showMessage();^
symbol: method showMessage()location: variable e of type Exception
ch10_06.java:22: error: cannot find symbollottoSize=e.changeSize();
^symbol: method changeSize()location: variable e of type Exception
2 errors
-
49
(1)Multi-catchcatchmethod2122showMessage()changeSize()CmyException1CmyException2methods
(2)19~23Multi-catch
10.4
1920212223::::::
catch(CmyException1 e){
e.showMessage();lottoSize=e.changeSize();
} catch(CmyException2 e){e.showMessage();lottoSize=e.changeSize();
}
50
(3)JDK7bugemethod
CmyException1CmyException2JDK7
JDK7bugJDK7Multi-catchmethod
methodMulti-catchcatch
10.4
-
51
10.4
106JDK7MulticatchmethodJDKbugJDK7MulticatchJDK7method10621~22emethodshowMessage()changeSize()JDK7106JDK7bugJDK7106JDK7Multicatchmethod
106JDK7MulticatchmethodJDKbugJDK7MulticatchJDK7method10621~22emethodshowMessage()changeSize()JDK7106JDK7bugJDK7106JDK7Multicatchmethod
10310619~23(2)
10310619~23(2)
52
10-510-5catch
10-710-7ch10_07.javamyJava\ch10\ch10_07.java
10.4
12345678910111213
/* :ch10_07.java : */
package myJava.ch10;import java.lang.*;import java.io.Console;
public class ch10_07 //{
public static void main(String args[]){
Console console=System.console();System.out.print(":");int lottoSize=0;
-
53
14151617181920212223242526272829303132333435363738394041
try{
lottoSize=Integer.parseInt(console.readLine()); if(lottoSize>48)
throw new CmyException1(":"); else if(lottoSize
-
55
10-5NumberFormatException23~27catchr
:r,66
10.4
56
try{
//}catch(1 | 2 | ){
//} catch(Exception ) {
//} finally{
//}
10.4
-
57
catchExceptioncatchExceptioncatch
10.4
Coding
trycatchcatchcatchcatchcatchJDK7Multicatchcatch(|)
Coding
trycatchcatchcatchcatchcatchJDK7Multicatchcatch(|)
58
10-8
10-8ch10_08.javamyJava\ch10\ch10_08.java
10.4
1234567891011121314
/* :ch10_08.java : */
package myJava.ch10;import java.lang.*;import java.io.Console;
public class ch10_08 //{
public static void main(String args[]){
Console console=System.console(); int lottoSize=0;int lottoAry[];
-
59
10.4
151617181920212223242526272829303132333435363738
while(true){
try{ System.out.print(":");lottoSize=Integer.parseInt(console.readLine()); lottoAry = new int[lottoSize]; break; //while
}catch(NumberFormatException e){System.out.println("");
} catch(Exception e){System.out.println("");
} finally{}
}System.out.println("...");
} }
60
(1)28~31catchExceptioncatchcatchr24~27catch-228~31catch(2)trycatchtrybreakcatchbreak
10.4:r:-2:3...
-
61
(1)30~33catchExceptioncatchcatchr26~29catch-230~33catch
(2)trycatchtrybreakcatchbreak
10.4
62
trycatchtrycatch(method)try
10.5 throws
-
63
throws
(1),(2)trycatch
[] [] () throws 1,2,{
//}
10.5 throws
64
(3)RuntimeException
10.5 throws
10-2
-
65
10-9
10-9ch10_09.javamyJava\ch10\ch10_09.java
10.5 throws
123456789101112
/* :ch10_09.java : */
package myJava.ch10;import java.lang.*;import java.io.Console;
public class ch10_09 //{
public static void main(String args[]){
CmyClass obj = new CmyClass();
66
1314151617181920212223242526272829303132333435
try{
obj.setValue(); //obj.printValue(); //
}catch(NumberFormatException e){
System.out.println(":");}catch(ArithmeticException e){
System.out.println(":0");} catch(Exception e){
System.out.println("");} finally{}
} }
10.5 throwstry
-
67
10.5 throws
3637383940414243444546474849505152535455
class CmyClass{
private int numerator,denominator; public Console console=System.console();
public void setValue() throws NumberFormatException{
System.out.print(":");numerator=Integer.parseInt(console.readLine()); System.out.print(":");denominator=Integer.parseInt(console.readLine()); System.out.println("");
}
public void printValue() throws ArithmeticException{
System.out.println("" + numerator/denominator);System.out.println("");
}}
68
(1)try15~16catch(2)41~54throws(3)NumberFormatExceptionArithmeticExceptionRuntimeException
:5:t:
:5:0:0
10.5 throws
-
69
RuntimeExceptionRuntimeExceptionRuntimeExceptionJVM
throwscatch
10.5 throws
70
10-9catchcatch
RuntimeException
10.5 throws
-
71
throwsthrowsthrowthrowsRuntimeException
JDKJavatrycatch
10.5 throws
72
throws10-1010-10ch10_10.javamyJava\ch10\ch10_10.java
10.6
1234567891011
/* :ch10_10.java : */
package myJava.ch10;import java.lang.*;import java.io.Console;
public class ch10_10 //{
public static void main(String args[]){
CmyClass2 obj2 = new CmyClass2();
-
73
1213141516171819202122232425262728293031323334
try{
obj2.run(); //}catch(NumberFormatException e){
System.out.println(":");}catch(ArithmeticException e){
System.out.println(":0");} catch(Exception e){
System.out.println("");} finally{}
} }
10.6
74
10.6 353637383940414243444546474849505152535455565758596061626364
class CmyClass1{
private int numerator,denominator; public Console console=System.console();
public void setValue() throws NumberFormatException{
System.out.print(":");numerator=Integer.parseInt(console.readLine()); System.out.print(":");denominator=Integer.parseInt(console.readLine()); System.out.println("");
}
public void printValue() throws ArithmeticException{
System.out.println("" + numerator/denominator);System.out.println("");
}}
class CmyClass2{
public CmyClass1 obj1 = new CmyClass1();public void run() throws NumberFormatException,ArithmeticException{
obj1.setValue(); //obj1.printValue(); //.
}}
run()run()(15)
-
75
10-9
(1)CmyClass1CmyClass2runrunrun15
(2)59RuntimeExceptionB-1B.8mainthrows IOException
10.6
76
readLineIOExceptionB-1B-1
B-1mainthrows IOExceptionreadLinemainmainIOExceptionRuntimeExceptionmainJVMJVM
10.6
-
77
mainmainthrows IOException
10-11B-1mainIOException10-11ch10_11.javamyJava\ch10\ch10_11.java
10.6
123456
/* :ch10_11.java :mainIOException */
package myJava.ch10;import java.lang.*;import java.io.*;
78
789101112131415161718192021222324252627282930
public class ch10_11 //{
public static void main(String args[]) //{
try{
BufferedReader buf;String str1,str2;
System.out.print(":");buf = new BufferedReader(new InputStreamReader(System.in));str1 = buf.readLine();System.out.print(":");str2 = buf.readLine();System.out.println(":");System.out.println(str1);System.out.println(str2);
}catch(IOException e){
//,}
}}
10.6
-
79
B-1
tryIOException
readLine
27
10.6
80
trycatch[finally]trycatch[finally]
trycatchfinallytry
10.7
-
81
10-12
10-12ch10_12.javamyJava\ch10\ch10_12.java
12345678910111213
/* :ch10_12.java : */
package myJava.ch10;import java.lang.*;import java.io.Console;
public class ch10_12 //{
public static void main(String args[]){
Console console=System.console(); int ary[]=new int[]{0,5,10,15,20,25,30,35,40,45};int x=0,num=0;
10.7
82
10.7
1415161718192021222324252627282930313233343536
try //try{
System.out.print(":");x=Integer.parseInt(console.readLine());
try{num=ary[x];System.out.println("ary[" + x + "]=" + num);
}catch(ArrayIndexOutOfBoundsException e){System.out.println(":!");
} }catch(NumberFormatException e) //catch{
System.out.println(":!");}
System.out.println("......"); }
}
-
83
(1)14~32trycatch19~27trytrycatch
(2)16,17,21,22172116~17trycatchtrycatch21,22
:r:!......
:15:!......
10.7
84
(3)trycatch
(4)trycatch16,17,21,22try
(5)16,17trycatchcatch
10.7
-
85
throw
5catchcatch
catchcatchcatch
10.8
86
10-13
10-13ch10_13.javamyJava\ch10\ch10_13.java
12345678910111213
/* :ch10_13.java : */
package myJava.ch10;import java.lang.*;import java.io.Console;
public class ch10_13 //{
public static void main(String args[]){
Console console=System.console(); int ary[]=new int[]{0,5,10,15,20,25,30,35,40,45};int x=0,num=0;
10.8
-
87
10.814151617181920212223242526272829303132333435363738394041
try //try{
try{
System.out.print(":");x=Integer.parseInt(console.readLine());num=ary[x];System.out.println("ary[" + x + "]=" + num);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println(":!");} catch(NumberFormatException e){
System.out.println(",");throw e;
}
}catch(NumberFormatException e) //catch{
System.out.println(":!");}
System.out.println("......"); }
}
34NumberFormatException
88
283034catch34catchcatch
:r,:!......
10.8
104101330104101330
-
89
(Precise rethrow with a final Exception)
JDK7Precise rethrow with a final Exception
methodtry-catchcatchcatch(Exception e)
methodcatch(Exception e)throws Exception
10.8
90
10.8
publicvoidtest()throwsException{try{//1,2
}catch(1e){
//}catch(2e){
//}catch(Exceptione){throwe;//
}}
-
91
test()test()
test()test()test()
10.8
publicvoidcaller(){try{Obj1.test();//1,2
}catch(Exceptione){//test()
}}
92
java.io.BufferedInputStreamread()
public int read() throws IOException
IOExceptionthrows Exception
10.8
-
93
test()
test()3434
test()
10.8
publicvoidtest()throws3,4,Exception{
test()}
94
10.8
publicvoidcaller(){try{Obj1.test();//1,2
}catch(3e){//test()3
}catch(4e){//test()4
}catch(Exceptione){//test()34
}}
-
95
JDK6JDK7
JDK7test()
JDK7test()throw eePrecise rethrow with a final Exception
10.8
publicvoidtest()throws3,4 //JDK7{
test()}
96
Precise rethrow with a final ExceptionJDK6JDK7
10.8
-
97
10-14
10-14ch10_14.javamyJava\ch10\ch10_14.java
10.8
12345678910111213141516171819
/* :ch10_14.java :Precise rethrow with a final Exception */
package myJava.ch10;import java.lang.*;import java.io.Console;
public class ch10_14 //{
public static void main(String args[]) {
Console console=System.console();System.out.print(":");int lottoSize=0;CmyClass1 obj1=new CmyClass1();
try{ lottoSize=obj1.check(console.readLine()); //
}
98
10.820212223242526272829303132333435363738394041424344454647
catch(CmyException1 e){
System.out.println(":6");lottoSize=6;
}catch(CmyException2 e){
System.out.println(":6");lottoSize=6;
} catch(NumberFormatException e){
System.out.println(",6");lottoSize=6;
} catch(Exception e){
System.out.println(":");} finally{
System.out.println("" + lottoSize);}
int lottoAry[] = new int[lottoSize];System.out.println("");
} }
-
99
10.8
4849505152
5354555657585960616263646566676869
class CmyClass1{
private int lottoSize; public void check(String inputStr)
throws CmyException1,CmyException2,NumberFormatException{try {
lottoSize=Integer.parseInt(inputStr); if(lottoSize>48)
throw new CmyException1(":"); else if(lottoSize
-
101
JDK6
JDK7
10.8
C:\myJava\ch10>javac ch10_14.javach10_14.java:67: unreported exception java.lang.Exception; must be caught or declared to be thrown
throw e;^
1 error
:5::66
:r,66
102
(1)18check()52check()CmyException1, CmyException2, NumberFormatExceptionException20~38
(2)CmyClass1check()63~66
NumberFormatException52
10.8
-
103
throws CmyException1, CmyException2, NumberFormatException, ExceptionJDK7, ExceptionJDK6, Exception63~66
(3)63finalfinal
10.8
trywithresourcesJDK7trycatchmulticatchPreciserethrowwithafinalException
trywithresourcesJDK7trycatchmulticatchPreciserethrowwithafinalException
104
(Error)
(Exception)
(Exception)
10.9
-
105
(1)Java
(2)(1)Java(2)
(3)java.lang.Exceptionjava.lang.ArithmeticException
(4)ThrowableException
(5)throw
10.9
106
(6)Javatrythrowcatchfinally(7)trycatch[finally]finally(8)trycatchcatch(9)catch(Exception )catch(10)throws throwsRuntimeException
10.9
-
107
(11)trycatch[finally]trycatch[finally]try
(12)JDK7try-catchcatchmulti-catchcatch(final Exception e){ throw e; }ExceptionthrowsPrecise rethrow with a final Exception
10.9
108
Q&A