Sunteți pe pagina 1din 67

Page 1 of 67

Chapter 5. Control Flow, Exception


Handling, and Assertions
Exam Objectives

if switch

break
continue,

try!catch!finally" #

$ %
& '
try catch finally
"

Supplementary Objectives

) *

+ #

5.1 Overview of Control Flow Statements


- #
#
# '

'if if-else switch

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 2 of 67

'while do-while for

'break continue return try-catch-finally assert

5.2 Selection Statements


. # #

if )

if-else )

switch )

Simple if Statement
if # '

if ( )

( #
/ 0
/ 0

if # / 0
( true / 0 if "
# ( false if
#
1 23

if

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 3 of 67

( # if
'

if (emergency) // emergency is a boolean variable


operate();

if (temperature > critical)


soundAlarm();

if (isLeapYear() && endOfCentury())


celebrate();

if (catIsAway()) { // Block
getFishingRod();
goFishing();
}

& / 0
# / > true

) / > boolean
' (a=b) #
#
a b

& if ( ;"
{}" 4

if (emergency); // Empty if block


operate(); // Executed regardless of whether it was an emergency or not.

if-else Statement
if-else # '

if ( )
1
else
2

( # #

/ 0 ( true / 10
if
" # ( false
/ 20
else " #
( # # else 5
if
1 23

( # if-else

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 4 of 67

'

if (emergency)
operate();
else
joinQueue();

if (temperature > critical)


soundAlarm();
else
businessAsUsual();

if (catIsAway()) {
getFishingRod();
goFishing();
} else
playWithCat();

) if

if (temperature >= upperLimit) { // (1)


if (danger) // (2) Simple if.
soundAlarm();
if (critical) // (3)
evacuate();
else // Goes with if at (3).
turnHeaterOff();
} else // Goes with if at (1).
turnHeaterOn();

{} if if
4" " # if
" -" # -"
6 '
#

// (A)
if (temperature > upperLimit) { // (1) Block notation.
if (danger) soundAlarm(); // (2)
} else // Goes with if at (1).
turnHeaterOn();

// (B)
if (temperature > upperLimit) // (1) Without block notation.
if (danger) soundAlarm(); // (2)
else turnHeaterOn(); // Goes with if at (2).

// (C)
if (temperature > upperLimit) // (1)
if (danger) // (2)
soundAlarm();
else // Goes with if at (2).
turnHeaterOn();

else else # if
# else

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 5 of 67

- if-else 6 if-else # if
if-else * else

if (temperature >= upperLimit) { // (1)


soundAlarm();
turnHeaterOff();
} else if (temperature < lowerLimit) { // (2)
soundAlarm();
turnHeaterOn();
} else if (temperature == (upperLimit-lowerLimit)/2) { // (3)
doingFine();
} else // (4)
noCauseToWorry();

if true
if ( 7"#
3" 8" false 7" true (
# else ( else

switch Statement

- switch
( #'

switch ( ) {
case 1
: 1
case 2
: 2

case n
: n
default:
9:
: #

switch switch # switch


# switch !long char
byte short int" switch
switch # switch
switch #'

switch

switch # case -
i # case 6 switch
4

( case 6 switch #
default

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 6 of 67

1 28 # switch

switch

4 default " switch


default switch (
case # switch

case # 6
# case switch
) 7; ;<" ( case
switch & case boolean long !

switch

public class Advice {

public final static int LITTLE_ADVICE = 0;


public final static int MORE_ADVICE = 1;
public final static int LOTS_OF_ADVICE = 2;

public static void main(String[] args) {


dispenseAdvice(LOTS_OF_ADVICE);
}

public static void dispenseAdvice(int howMuchAdvice) {


switch(howMuchAdvice) { // (1)
case LOTS_OF_ADVICE:
System.out.println("See no evil."); // (2)
case MORE_ADVICE:
System.out.println("Speak no evil."); // (3)
case LITTLE_ADVICE:
System.out.println("Hear no evil."); // (4)
break; // (5)
default:
System.out.println("No advice."); // (6)
}
}
}

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 7 of 67

= '

See no evil.
Speak no evil.
Hear no evil.

( > 23 howMuchAdvice
switch 3" dispenseAdvice() #
# howMuchAdvice LOTS_OF_ADVICE ( switch
8" -
7" - ;"
break 2" switch
break 2" #
# > break switch
switch ) 2; 3?8" (
howMuchAdvice MORE_ADVICE 7" ;"
LITTLE_ADVICE ;" 4
default #

case #
" case case
case LITTLE_ADVICE > 23 #
;" 2"

> 28 break switch char


# > & break
# case (
break switch

break switch

public class Digits {

public static void main(String[] args) {


System.out.println(digitToString('7') + " " +
digitToString('8') + " " +
digitToString('6'));
}

public static String digitToString(char digit) {


String str = "";
switch(digit) {
case '1': str = "one"; break;
case '2': str = "two"; break;
case '3': str = "three"; break;
case '4': str = "four"; break;
case '5': str = "five"; break;
case '6': str = "six"; break;
case '7': str = "seven"; break;
case '8': str = "eight"; break;
case '9': str = "nine"; break;
case '0': str = "zero"; break;
default: System.out.println(digit + " is not a digit!");
}
return str;

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 8 of 67

}
}

= '

seven eight six

) case #
> 27 switch 3"

switch case
# #

) # case
switch ( # switch ) switch
# case # case
#
) ;2 387" ( > 27 switch
8" # switch
# switch 4 break
switch #

! " switch

public class Seasons {

public static void main(String[] args) {


int monthNumber = 11;
switch(monthNumber) { // (1) Outer
case 12: case 1: case 2:
System.out.println("Snow in the winter.");
break;
case 3: case 4: case 5:
System.out.println("Green grass in spring.");
break;
case 6: case 7: case 8:
System.out.println("Sunshine in the summer.");
break;
case 9: case 10: case 11: // (2)
switch(monthNumber) { // Nested switch (3) Inner
case 10:
System.out.println("Halloween.");
break;
case 11:
System.out.println("Thanksgiving.");
break;
} // end nested switch
// Always printed for case labels 9, 10, 11
System.out.println("Yellow leaves in the fall."); // (4)
break;
default:
System.out.println(monthNumber + " is not a valid month.");
}
}
}

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 9 of 67

= '

Thanksgiving.
Yellow leaves in the fall.

Review Questions

# # @

public class IfTest {


public static void main(String[] args) {
if (true)
if (false)
System.out.println("a");
else
System.out.println("b");
}
}

) #

# if

# # #
# if else

# a#

" # b#

# #

) #

if

# (a b boolean (a = b)
if

4 if if else

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 10 of 67

" if (false) ; else ;

= # boolean
if

# # # @

void test(int x) {
switch (x) {
case 1:
case 2:
case 0:
default:
case 4:
}
}

) #

x switch

# case 0 case 1

> case # break

" default switch

switch

# #

$ switch case
# switch @

) #

switch int case char

# switch float case int

switch byte case float

" switch char case long

switch boolean case boolean

5.3 Iteration Statements

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 11 of 67

# "4
" #

. '

while

do-while

for

#
while for # do-while

while Statement
while

while ( )

while
true false
# # (
false # ( # while
% boolean #
while # 1 27

while

while # #

while (noSignOfLife())
keepLooking();

) #
;"

while (noSignOfLife()); // Empty statement as loop body!

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 12 of 67

keepLooking(); // Statement not in the loop body.

do-while Statement
do-while

do

while ( );

do-while
false false
# #
& 1 2; # do-
while

$ do-while

do-while (
while do-while ( #
# 3"
" 8"

while (cat.isAway()) { // (1)


mice.play();
}

do { // (2)
mice.play();
} while (cat.isAway());

for Statement
for ( !
# #

#'

for ( ; ; )

/ 0 %

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 13 of 67

/ 0 / 0 boolean
true 5 #
# # for 4 "
/ 0

& / 0
for 1 22 % #
6 while '

while ( ) {

for

# int

int sum = 0;
int[] array = {12, 23, 5, 7, 19};
for (int index = 0; index < array.length; index++) // (1)
sum += array[index];

index % / 0 (
/ 0 for
for # / 0 /
0 / 0 / 0

3" # # / 0
) !

for (int i = 0, j = 1, k = 2; ... ; ...) ...; // (2)

i j k int 4
/ 0 for
A# # #
int String" 6

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 14 of 67

for (int i = 0, String str = "@"; ... ; ...) ...; // (3) Compile time error.

/ 0 !
) ;7 337" 1 8" #

int i, j, k; // Variable declaration


for (i = 0, j = 1, k = 2; ... ; ...) ...; // (4) Just initialization

/ 0 # !
# & i j k #

+ # / 0
2" # 1 B"
!

// (5) Not legal and ugly.


for (int i = 0, System.out.println("This won't do!"); flag; i++) {
// loop body
}

// (6) Legal, but still ugly.


int i;
for (i = 0, System.out.println("This is legal!"); flag; i++) {
// loop body
}

/ 0 !
# for !
/ 0 ! # /
0

// Legal usage but not recommended.


int[][] sqMatrix = { {3, 4, 6}, {5, 7, 4}, {5, 8, 9} };
for (int i = 0, j = sqMatrix[0].length - 1, asymDiagonal = 0; // initialization
i < sqMatrix.length; // loop condition
i++, j--) // increment expression
asymDiagonal += sqMatrix[i][j]; // loop body

4 for! 4 #
( / 0
true C C (;;) #

"
'

for (;;) Java.programming(); // Infinite loop

5.4 Transfer Statements


. '

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 15 of 67

break

continue

return

try-catch-finally

throw

assert

& . goto goto #

Labeled Statements
4

4 #
# #

L1: if (i > 0) {
L1: System.out.println(i); // (1) Not OK. Label redeclared.
}

L1: while (i < 0) { // (2) OK.


L2: System.out.println(i);
}

L1: { // (3) OK. Labeled block.


int j = 10;
System.out.println(j);
}

L1: try { // (4) OK. Labeled try-catch-finally block.


int j = 10, k = 0;
L2: System.out.println(j/k);
} catch (ArithmeticException ae) {
L3: ae.printStackTrace();
} finally {
L4: System.out.println("Finally done.");
}

4 '

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 16 of 67

LabelA: LabelB: System.out.println("Mutliple labels. Use judiciously.");

4 '

L0: int i = 0; // Compile time error.

4 # ! break continue
#

break Statement
break # '

break; // the unlabeled form

break <label>; // the labeled form

break for while do-while) switch


# break
"
#

( > 2; break 3" for -


8"# i 6 4 3"

> 2; # break
switch break break 7"
for # j 6 2 switch ;"
for

$ break

class BreakOut {

public static void main(String[] args) {

for (int i = 1; i <= 5; ++i) {


if (i == 4) break; // (1) Terminate loop. Control to (2).
// Rest of loop body skipped when i gets the value 4.
System.out.println(i + "\t" + Math.sqrt(i));
} // end for
// (2) Continue here.

int n = 2;
switch (n) {
case 1: System.out.println(n); break;
case 2: System.out.println("Inner for loop: ");
for (int j = 0; j < n; j++)
if (j == 2)
break; // (3) Terminate loop. Control to (4).
else
System.out.println(j);
default: System.out.println("default: " + n); // (4) Continue here.

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 17 of 67

}
}
}

= '

1 1.0
2 1.4142135623730951
3 1.7320508075688772
Inner for loop:
0
1
default: 2

4 break break
- #
( #
# '

out:
{ // (1) Labeled block
// ...
if (j == 10) break out; // (2) Terminate block. Control to (3).
System.out.println(j); // Rest of the block not executed if j == 10.
// ...
}
// (3) Continue here.

( > 22 # 6
3E # for 3" 8"
outer 3" break 7" 2"#

break ;" B"#

outer"

%# " break

class LabeledBreakOut {
public static void main(String[] args) {
int[][] squareMatrix = {{4, 3, 5}, {2, 1, 6}, {9, 7, 8}};
int sum = 0;
outer: // label
for (int i = 0; i < squareMatrix.length; ++i){ // (1)
for (int j = 0; j < squareMatrix[i].length; ++j) { // (2)
if (j == i) break; // (3) Terminate this loop.
// Control to (5).
System.out.println("Element[" + i + ", " + j + "]: " +
squareMatrix[i][j]);
sum += squareMatrix[i][j];
if (sum > 10) break outer;// (4) Terminate both loops.
// Control to (6).
} // end inner loop
// (5) Continue with outer loop.
} // end outer loop
// (6) Continue here.

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 18 of 67

System.out.println("sum: " + sum);


}
}

= '

Element[1, 0]: 2
Element[2, 0]: 9
sum: 11

continue Statement
break continue # '

continue; // the unlabeled form


continue <label>; // the labeled form

continue for while do-while


# (
while do-while
# # / ( for
# # /

( > 2B continue for -


8"# i 6 4 3"
# for

& continue

class Skip {
public static void main(String[] args) {
for (int i = 1; i <= 5; ++i) {
if (i == 4) continue; // (1) Control to (2).
// Rest of loop body skipped when i has the value 4.
System.out.println(i + "\t" + Math.sqrt(i));
// (2). Continue with increment expression.
} // end for
}
}

= '

1 1.0
2 1.4142135623730951
3 1.7320508075688772
5 2.23606797749979

4 continue # >
continue
( > 2? continue 7" 2"#
5 #
continue ;" B"#
#

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 19 of 67

outer" ( > 22 break"


> 2? continue"

'% # " continue

class LabeledSkip {
public static void main(String[] args) {
int[][] squareMatrix = {{4, 3, 5}, {2, 1, 6}, {9, 7, 8}};
int sum = 0;
outer: // label
for (int i = 0; i < squareMatrix.length; ++i){ // (1)
for (int j = 0; j < squareMatrix[i].length; ++j) { // (2)
if (j == i) continue; // (3) Control to (5).
System.out.println("Element[" + i + ", " + j + "]: " +
squareMatrix[i][j]);
sum += squareMatrix[i][j];
if (sum > 10) continue outer; // (4) Control to (6).
// (5) Continue with inner loop.
} // end inner loop
// (6) Continue with outer loop.
} // end outer loop
System.out.println("sum: " + sum);
}
}

= '

Element[0, 1]: 3
Element[0, 2]: 5
Element[1, 0]: 2
Element[1, 2]: 6
Element[2, 0]: 9
sum: 25

return Statement
return
" # return
# void !void
& # void

/
) 7; BB" 4
23 !void return 4 void
return D #
F return
> 2<
return % 23

# return

return ( void ) " ( ! *void ) "


return; #

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 20 of 67

return ; #

+ return

public class ReturnDemo {

public static void main (String[] args) { // (1) void method can use return.
if (args.length == 0) return;
output(checkValue(args.length));
}

static void output(int value) { // (2) void method need not use return.
System.out.println(value);
return 'a'; // Not OK. Cannot return a value.
}

static int checkValue(int i) { // (3) non-void method must return a value.


if (i > 3)
return i; // OK.
else
return 2.0; // Not OK. double not assignable to int.
}
}

Review Questions

# # @

class MyClass {
public static void main(String[] args) {
boolean b = false;
int i = 1;
do {
i++;
b = ! b;
} while (b);
System.out.println(i);
}
}

) #

# b
do-while

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 21 of 67

# # b = ! b #

# # # 1#

" # # # 2#

# # # 3#

& # # # @

public class MyClass {


public static void main(String[] args) {
int i=0;
int j;
for (j=0; j<10; ++j) { i++; }
System.out.println(i + " " + j);
}
}

) # #

# 9

# # 10

# 11

" # 9

# 10

# 11

' for @

) #

int j=10; for (int i=0, j+=90; i<j; i++) { j--; }

# for (int i=10; i=0; i--) {}

for (int i=0, j=100; i<j; i++, --j) {;}

" int i, j; for (j=100; i<j; j--) { i += 2; }

int i=100; for ((i>0); i--) {}

+ # # @

class MyClass {

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 22 of 67

public static void main(String[] args) {


int i = 0;
for ( ; i<10; i++) ; // (1)
for (i=0; ; i++) break; // (2)
for (i=0; i<10; ) i++; // (3)
for ( ; ; ) ; // (4)
}
}

) #

# for 3"

# # for 8"

# for 7"

" # for ;"

# # #
#

# # # #

, # # @0

) #

while () break;

# do { break; } while (true);

if (true) { break; }

" switch (1) { default: break; }

for (;true;) break;

- G # # # #
@

outer:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
if (i == j) {
continue outer;
}
System.out.println("i=" + i + ", j=" + j);
}

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 23 of 67

) # #

i=1, j=0

# i=0, j=1

i=1, j=2

" i=2, j=1

i=2, j=2

i=3, j=3

i=3, j=2

# # @

class MyClass {
public static void main(String[] args) {
for (int i = 0; i<10; i++) {
switch(i) {
case 0:
System.out.println(i);
}
if (i) {
System.out.println(i);
}
}
}
}

) #

# # switch switch

# # # if

# # # 0 10 #

" # # # 0#

# # # 0 # #

# # # 1 10 #

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 24 of 67

# max() #
@

// (1)
int max(int x, int y) {
return (if (x > y) { x; } else { y; });
}
// (2)
int max(int x, int y) {
return (if (x > y) { return x; } else { return y; });
}
// (3)
int max(int x, int y) {
switch (x < y) {
case true:
return y;
default:
return x;
};
}
// (4)
int max(int x, int y) {
if (x>y) return x;
return y;
}

) #

( 3"

# ( 8"

( 7"

" ( ;"

G # # @

class MyClass {
public static void main(String[] args) {
int k=0;
int l=0;
for (int i=0; i <= 3; i++) {
k++;
if (i == 2) break;
l++;
}
System.out.println(k + ", " + l);
}
}

) #

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 25 of 67

# # 3, 3 #

# 4, 3 # break continue

" # break return

# break

$ @

) # #

{{}}

# { continue; }

block: { break block; }

" block: { continue block; }

break while do-while for"


switch

5.5 Stack-based Execution and Exception Propagation


4 .
1 6
# >
.
#

#! !

# 4
# #
# # # #! !
try!catch!finally

) .
HI - J" > #
"
> "
> # # #
#

>
# #

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 26 of 67

4
# F

> 2J (
( '

main() # printAverage() #
3"

printAverage() computeAverage() 7"

computeAverage()
?"

,) "

public class Average1 {

public static void main(String[] args) {


printAverage(100,0); // (1)
System.out.println("Exit main()."); // (2)
}

public static void printAverage(int totalSum, int totalNumber) {


int average = computeAverage(totalSum, totalNumber); // (3)
System.out.println("Average = " + // (4)
totalSum + " / " + totalNumber + " = " + average);
System.out.println("Exit printAverage()."); // (5)
}

public static int computeAverage(int sum, int number) {


System.out.println("Computing average."); // (6)
return sum/number; // (7)
}
}

= '

Computing average.
Average = 100 / 20 = 5
Exit printAverage().
Exit main().

> > 2J 1
2B > # #
#
System.out.println() B" 1 2B
'main() printAverage() computeAverage() 2
computeAverage() ?" 1 2B
# 6 1 2B

& ) "

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 27 of 67

( 3" > 2J

printAverage(100, 20); // (1)

printAverage(100, 0); // (1)

#'

Computing average.
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Average1.computeAverage(Average1.java:18)
at Average1.printAverage(Average1.java:10)
at Average1.main(Average1.java:5)

1 2? 4 # return ?"
computeAverage() 4
sum/number E
.HI ArithmeticException C
> C 3<2"
.
HI

' .

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 28 of 67

1 2? # #
# ( 1 2? computeAverage()
# # return
?" ) #
#
#
# printAverage()"
# ;" 2"
printAverage() #
main()" # main()
8" main() )
# F
#
# # # 4
#

( # !
) #
"

( #
.
( . ! ! " .
HI . 8)+K'

>java -Djava.compiler=NONE Average1

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 29 of 67

5.6 Exception Types


> . * 4 java.lang. Throwable
1 2< # Throwable #
Exception Error
1 2< #

+ . ( /

Throwable String

4 # !

Throwable # 6 '

String getMessage()

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 30 of 67

void printStackTrace()

L
6 # # #
# PrintStream PrintWriter
# printStackTrace()

String toString()

$ #
# getMessage()

Class Exception
Exception # # #
( RuntimeException
"= Exception
(
:=! IOException
FileNotFoundException EOFException" G,(! AWTException"

Class RuntimeException

$ ! ! ArrayIndexOutOfBounds Exception"
% NullPointerException"
ClassCastException" IllegalArgumentException" %
ArithmeticException" NumberFormatException"
java.lang.RuntimeException # Exception
4

Class Error
AssertionError java.lang.Error .
) 23E 8E<" = java.lang.Error
LinkageError" ThreadDeath"
VirtualMachineError"

Checked and Unchecked Exceptions


> RuntimeException Error
#
#
) 2J 8E3"

> Error RuntimeException #

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 31 of 67

#
# # 1 2<" Error
" #
RuntimeException " #

Defining New Exceptions


&# ! %
#
# &# Exception
#

4
# # super()
# &
* # 6
# #

public class EvacuateException extends Exception {


// Data
Date date;
Zone zone;
TransportMode transport;

// Constructor
public EvacuateException(Date d, Zone z, TransportMode t) {
// Call the constructor of the superclass
super("Evacuation of zone " + z);
// ...
}
// Methods
// ...
}

) 6

5.7 Exception Handling: try, catch, and finally


try!catch!finally #
# '

try { // try block


<statements>
} catch (<exception type1> <parameter1>) { // catch block
<statements>
}
...
catch (<exception typen> <parametern>) { // catch block
<statements>
} finally { // finally block

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 32 of 67

<statements>
}

> # try catch 4


finally try
# catch # 1 2J # #
try-catch-finally

, try-catch-finally 0 1

4 #
1 try % catch finally catch
finally # * # try
4 try # catch finally >
catch catch
# #
Throwable

> try catch finally" try-catch-finally


# try-catch-finally A#

try Block
try #
try

1 try catch
finally 3" 1 2J"

1 try catch
D D catch 8" 1 2J" (
catch # finally

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 33 of 67

7" 1 2J"

catch Block

= try catch 4
catch #
catch ) BB 8BE" catch
catch

= catch
# (

4 catch # finally
# finally # catch
#

( > 23E printAverage() computeAverage() try!catch


;" catch ArithmeticException
catch
?" <" > 1 23E # #
try # #
try!catch ) 3 1 2J

- try-catch 2

public class Average2 {

public static void main(String[] args) {


printAverage(100, 0); // (1)
System.out.println("Exit main()."); // (2)
}

public static void printAverage(int totalSum, int totalNumber) {


try { // (3)
int average = computeAverage(totalSum, totalNumber); // (4)
System.out.println("Average = " + // (5)
totalSum + " / " + totalNumber + " = " + average);
} catch (ArithmeticException ae) { // (6)
ae.printStackTrace(); // (7)
System.out.println("Exception handled in " +
"printAverage()."); // (8)
}
System.out.println("Exit printAverage()."); // (9)
}

public static int computeAverage(int sum, int number) {


System.out.println("Computing average."); // (10)
return sum/number; // (11)
}
}

= # printAverage(100, 20) 3"


'

Computing average.

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 34 of 67

Average = 100 / 20 = 5
Exit printAverage().
Exit main().

= # printAverage(100, 0) 3"
'

Computing average.
java.lang.ArithmeticException: / by zero
at Average2.computeAverage(Average2.java:24)
at Average2.printAverage(Average2.java:11)
at Average2.main(Average2.java:5)
Exception handled in printAverage().
Exit printAverage().
Exit main().

- / " 3 4

A# # > 23E# # 3"


'

printAverage(100, 0)

ArithmeticException # computeAverage() 1
1 233# computeAverage()
printAverage() # catch B"
& J" try!catch #
J" 8" ) 8 1 2J

/ " 3 4

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 35 of 67

( > 233 main() printAverage() try!catch


3" catch 7" ArithmeticException
printAverage() computeAverage() try!catch ?"
catch IllegalArgumentException
> 1 238 # # ArithmeticException
catch printAverage() catch
catch main()
# & B"

/ " 3 4

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 36 of 67

& try ?" printAverage() '


J" catch 3E"
printAverage() ' 37"
) 7 1 2J

public class Average3 {

public static void main(String[] args) {


try { // (1)
printAverage(100, 0); // (2)
} catch (ArithmeticException ae) { // (3)
ae.printStackTrace(); // (4)
System.out.println("Exception handled in " +
"main()."); // (5)
}
System.out.println("Exit main()."); // (6)
}

public static void printAverage(int totalSum, int totalNumber) {


try { // (7)
int average = computeAverage(totalSum, totalNumber); // (8)
System.out.println("Average = " + // (9)
totalSum + " / " + totalNumber + " = " + average);
} catch (IllegalArgumentException iae) { // (10)
iae.printStackTrace(); // (11)
System.out.println("Exception handled in " +
"printAverage()."); // (12)
}
System.out.println("Exit printAverage()."); // (13)
}

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 37 of 67

public static int computeAverage(int sum, int number) {


System.out.println("Computing average."); // (14)
return sum/number; // (15)
}
}

= '

Computing average.
java.lang.ArithmeticException: / by zero
at Average3.computeAverage(Average3.java:30)
at Average3.printAverage(Average3.java:17)
at Average3.main(Average3.java:6)
Exception handled in main().
Exit main().

catch 4
* catch
) BB 8BE" ( catch * 6
* javac catch
# catch catch
# # #
catch 3" 8" # # ' Exception #
# ArithmeticException

...
// Compiler complains
catch (Exception e) { // (1) superclass
System.out.println(e);
} catch (ArithmeticException e) { // (2) subclass
System.out.println(e);
}
...

finally Block

( try finally
# catch # ) finally #
!
"

4 try!finally # #
#

int sum = -1;


try {
sum = sumNumbers();
// other actions
} finally {
if (sum >= 0) calculateAverage();
}

try sumNumbers() #
calculateAverage() # finally #

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 38 of 67

try 4 calculateAverage()
sumNumbers() sum calculateAverage()
catch

( finally #
return break try catch #
finally 1 2J 3<J"

( # try
catch finally

( #
catch # catch # "
finally

( finally # #
D # try catch # (
#

( finally return break


# # D #
try catch # ( return
finally # return
try catch

= > 238 # finally J" #


# try 7" ( #
catch B" 4 finally J"
3E"

try-catch-finally 2

public class Average4 {

public static void main(String[] args) {


printAverage(100, 20); // (1)
System.out.println("Exit main()."); // (2)
}

public static void printAverage(int totalSum, int totalNumber) {


try { // (3)
int average = computeAverage(totalSum, totalNumber); // (4)
System.out.println("Average = " + // (5)
totalSum + " / " + totalNumber + " = " + average);
} catch (ArithmeticException ae) { // (6)
ae.printStackTrace(); // (7)
System.out.println("Exception handled in " +
"printAverage()."); // (8)
} finally { // (9)
System.out.println("Finally done.");
}
System.out.println("Exit printAverage()."); // (10)
}

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 39 of 67

public static int computeAverage(int sum, int number) {


System.out.println("Computing average."); // (11)
return sum/number; // (12)
}
}

= # printAverage(100, 20) 3"


'

Computing average.
Average = 100 / 20 = 5
Finally done.
Exit printAverage().
Exit main().

= # printAverage(100, 0) 3"
'

Computing average.
java.lang.ArithmeticException: / by zero
at Average4.computeAverage(Average4.java:26)
at Average4.printAverage(Average4.java:11)
at Average4.main(Average4.java:5)
Exception handled in printAverage().
Finally done.
Exit printAverage().
Exit main().

= finally
> 237
printAverage() finally B"
ArithmeticException # J" (
& > 238
> 237

try-finally 2

public class Average5 {

public static void main(String[] args) {


printAverage(100, 0); // (1)
System.out.println("Exit main()."); // (2)
}

public static void printAverage(int totalSum, int totalNumber) {


try { // (3)
int average = computeAverage(totalSum, totalNumber); // (4)
System.out.println("Average = " + // (5)
totalSum + " / " + totalNumber + " = " + average);
} finally { // (6)
System.out.println("Finally done.");
}
System.out.println("Exit printAverage()."); // (7)
}

public static int computeAverage(int sum, int number) {


System.out.println("Computing average."); // (8)
return sum/number; // (9)
}

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 40 of 67

= '

Computing average.
Finally done.
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Average5.computeAverage(Average5.java:21)
at Average5.printAverage(Average5.java:10)
at Average5.main(Average5.java:4)

> 23; # # return


finally #
return <" finally
return B" try #
ArithmeticException # computeAverage()
printAverage() return finally &
return <" # E
printAverage()

$ finally 0 1 " return

public class Average6 {

public static void main(String[] args) {


System.out.println("Average: " + printAverage(100, 20)); // (1)
System.out.println("Exit main()."); // (2)
}

public static int printAverage(int totalSum, int totalNumber) {


int average = 0;
try { // (3)
average = computeAverage(totalSum, totalNumber); // (4)
System.out.println("Average = " + // (5)
totalSum + " / " + totalNumber + " = " + average);
return average; // (6)
} finally { // (7)
System.out.println("Finally done.");
return average*2; // (8)
}
}

public static int computeAverage(int sum, int number) {


System.out.println("Computing average."); // (9)
return sum/number; // (10)
}
}

= # printAverage(100, 20) 3"


'

Computing average.
Average = 100 / 20 = 5
Finally done.
Average: 10
Exit main().

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 41 of 67

= # printAverage(100, 0) 3"
'

Computing average.
Finally done.
Average: 0
Exit main().

5.8 throw Statement


> # # #
4 # throw
throw #'

throw ;

/ 0 Throwable
4 NullPointerException # / 0
null Throwable # # 4
# *

throw new ArithmeticException("Integer division by 0");

#
catch try
try
4 finally try
( #
( # catch

( > 232 # throw 3?"


main() # catch 7" &
finally B" 3;" > ?"

public class Average7 {

public static void main(String[] args) {


try { // (1)
printAverage(100, 0); // (2)
} catch (ArithmeticException ae) { // (3)
ae.printStackTrace(); // (4)
System.out.println("Exception handled in " + // (5)
"main().");
} finally {
System.out.println("Finally in main()."); // (6)
}
System.out.println("Exit main()."); // (7)

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 42 of 67

public static void printAverage(int totalSum, int totalNumber) {


try { // (8)
int average = computeAverage(totalSum, totalNumber); // (9)
System.out.println("Average = " + // (10)
totalSum + " / " + totalNumber + " = " + average);
} catch (IllegalArgumentException iae) { // (11)
iae.printStackTrace(); // (12)
System.out.println("Exception handled in " + // (13)
"printAverage().");
} finally {
System.out.println("Finally in printAverage()."); // (14)
}
System.out.println("Exit printAverage()."); // (15)
}

public static int computeAverage(int sum, int number) {


System.out.println("Computing average.");
if (number == 0) // (16)
throw new ArithmeticException("Integer division by 0");// (17)
return sum/number; // (18)
}
}

= '

Computing average.
Finally in printAverage().
java.lang.ArithmeticException: Integer division by 0
at Average7.computeAverage(Average7.java:35)
at Average7.printAverage(Average7.java:19)
at Average7.main(Average7.java:6)
Exception handled in main().
Finally in main().
Exit main().

5.9 throws Clause


4 throws

... someMethod(...)
throws ! 1
, ! 2
,..., ! n
{ ... }

> ! i
# throws =
# throws
* *
* ) B3 88B" throws

A % ) <8 773

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 43 of 67

4 # throw
#
# # (

try #

try #
throws

# throws

#
# # ( #
& throws

4 # > 23B
IntegerDivisionByZero 33" Exception

( > 23B main() printAverage() try 3" (


if J" computeAverage() #
IntegerDivisionByZero 33" & computeAverage()
printAverage() #
throws B" <" main()
) printAverage() # try 3" main
() # catch 7"
finally ;" # 2" (
main() # throws
( #

& throws 2

public class Average8 {


public static void main(String[] args) {
try { // (1)
printAverage(100, 0); // (2)
} catch (IntegerDivisionByZero idbze) { // (3)
idbze.printStackTrace();
System.out.println("Exception handled in " +
"main().");
} finally { // (4)
System.out.println("Finally done in main().");
}

System.out.println("Exit main()."); // (5)


}

public static void printAverage(int totalSum, int totalNumber)


throws IntegerDivisionByZero { // (6)

int average = computeAverage(totalSum, totalNumber);


System.out.println("Average = " +

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 44 of 67

totalSum + " / " + totalNumber + " = " + average);


System.out.println("Exit printAverage()."); // (7)
}

public static int computeAverage(int sum, int number)


throws IntegerDivisionByZero { // (8)

System.out.println("Computing average.");
if (number == 0) // (9)
throw new IntegerDivisionByZero("Integer Division By Zero");
return sum/number; // (10)
}
}

class IntegerDivisionByZero extends Exception { // (11)


IntegerDivisionByZero(String str) { super(str); } // (12)
}

= '

Computing average.
IntegerDivisionByZero: Integer Division By Zero
at Average8.computeAverage(Average8.java:33)
at Average8.printAverage(Average8.java:22)
at Average8.main(Average8.java:7)
Exception handled in main().
Finally done in main().
Exit main().

throws
# #
throws ( # A B
C# D throws A B C
* D ( printAverage()
Exception IntegerDivisionByZero throws

public static void printAverage(int totalSum, int totalNumber)


throws Exception { /* ... */ }

( throws
# #
L # #
#

4 #
) B8 877" # #
throws @
" throws
#
throws 4 #
# # #
) # *
" # #

class A {
// ...

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 45 of 67

protected void superclassMethodX()


throws FirstException, SecondException, ThirdException {/* ... */} // (1)
// ...
}

class B extends A {
// ...
protected void superclassMethodX()
throws FirstException, ThirdException { /* ... */ } // (2)
// ...

( superclassMethodX A B
throws B 8"
3"

Review Questions

# # # # @

public class MyClass {


public static void main(String[] args) {
int k=0;
try {
int i = 5/k;
} catch (ArithmeticException e) {
System.out.println("1");
} catch (RuntimeException e) {
System.out.println("2");
return;
} catch (Exception e) {
System.out.println("3");
} finally {
System.out.println("4");
}
System.out.println("5");
}
}

) #

# 5

# # 1 4

# 1 2 4

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 46 of 67

" # 1 4 5

# 1 2 4 5

# 3 5

& G # # @

public class Exceptions {


public static void main(String[] args) {
try {
if (args.length == 0) return;
System.out.println(args[0]);
} finally {
System.out.println("The end");
}
}
}

) # #

( # #

# ( # # "The end"

# # ArrayIndexOutOfBoundsException

" ( # #

( # # #
"The end"

' # # @

public class MyClass {


public static void main(String[] args) {
RuntimeException re = null;
throw re;
}
}

) #

# main()
# RuntimeException

# # # re

# # # #
java.lang.RuntimeException #

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 47 of 67

" # # # #
java.lang.NullpointerException #

# # # #

+ @

) # #

( #
#

# 4 #

main() #

" 4 # #

finally # #
try

, # # # #
@

public class MyClass {


public static void main(String[] args) {
try {
f();
} catch (InterruptedException e) {
System.out.println("1");
throw new RuntimeException();
} catch (RuntimeException e) {
System.out.println("2");
return;
} catch (Exception e) {
System.out.println("3");
} finally {
System.out.println("4");
}
System.out.println("5");
}
// InterruptedException is a direct subclass of Exception.
static void f() throws InterruptedException {
throw new InterruptedException("Time for lunch.");
}
}

) #

# 5

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 48 of 67

# # 1 4

# 1 2 4

" # 1 4 5

# 1 2 4 5

# 3 5

- # # # # @

public class MyClass {


public static void main(String[] args) throws InterruptedException {
try {
f();
System.out.println("1");
} finally {
System.out.println("2");
}
System.out.println("3");
}
// InterruptedException is a direct subclass of Exception.
static void f() throws InterruptedException {
throw new InterruptedException("Time to go home.");
}
}

) #

# 2 # InterruptedException.

# # 1 2

# 1 2 3

" # 2 3

# 3 2

# 1 3

# # # @

public class MyClass {


public static void main(String[] args) throws A {
try {
f();
} finally {
System.out.println("Done.");
} catch (A e) {
throw e;

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 49 of 67

}
}

public static void f() throws B {


throw new B();
}
}
class A extends Throwable {}

class B extends A {}

) #

main() # B

# finally # catch main()

catch main() B
A

" 4 try # finally catch

f()
# throws # @

class A {
// InterruptedException is a direct subclass of Exception.
void f() throws ArithmeticException, InterruptedException {
div(5, 5);
}
int div(int i, int j) throws ArithmeticException {
return i/j;
}
}

public class MyClass extends A {


void f() /* throws [...list of exceptions...] */ {
try {
div(5, 0);
} catch (ArithmeticException e) {
return;
}
throw new RuntimeException("ArithmeticException was expected.");
}
}

) #

# & # ArithmeticException

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 50 of 67

& # InterruptedException

" & # RuntimeException

& # ArithmeticException
InterruptedException

# # @

class A {
void f() throws ArithmeticException {
//...
}
}

public class MyClass extends A {


public static void main(String[] args) {
A obj = new MyClass();

try {
obj.f();
} catch (ArithmeticException e) {
return;
} catch (Exception e) {
System.out.println(e);
throw new RuntimeException("Something wrong here");
}
}
// InterruptedException is a direct subclass of Exception.
void f() throws InterruptedException {
//...
}
}

) #

main() # RuntimeException

# f() MyClass #
ArithmeticException f() A

f() MyClass # #
InterruptedException f() A #

" # catch(ArithmeticException) #
catch(Exception)

M # catch

& # # # #

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 51 of 67

5.10 Assertions
4 .
>
true # ( false #

"( #
",
* #

assert Statement and AssertionError Class

# # assert '

assert <boolean expression> ; // the simple form


assert <boolean expression> : <message expression> ; // the augmented form

( 838" assert #
1 237 # 6 # '

if (<assertions enabled> && !<boolean expression>) // the simple form


throw new AssertionError();

if (<assertions enabled> && !<boolean expression>) // the augmented form


throw new AssertionError(<message expression>);

assert 36
# "4

( ( true
assert A# false AssertionError #
( AssertionError

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 52 of 67

( false
AssertionError
" AssertionError
(
void #

8" 7" ;" Speed > 23?" (


6 8" 7" ;"
calcSpeed() 8" ;"

assert distance >= 0.0; // (2)


...
assert speed >= 0.0; // (4)

7"

assert time > 0.0 : "Time is not a positive value: " + time; // (3)

7" 6 # '

if (time <= 0.0) throw new AssertionError("Time is not a positive value: " + time);

java.lang.AssertionError java.lang.Error 1 2<"


AssertionError try-catch
# # A# Error
AssertionError
- # #

( assert " AssertionError


! ' byte short
int" *
# (
6 AssertionError * A#
getMessage() #

'

public class Speed {

public static void main(String[] args) {


Speed objRef = new Speed();
double speed = objRef.calcSpeed(-12.0, 3.0); // (1a)
// double speed = objRef.calcSpeed(12.0, -3.0); // (1b)
// double speed = objRef.calcSpeed(12.0, 2.0); // (1c)
// double speed = objRef.calcSpeed(12.0, 0.0); // (1d)
System.out.println("Speed (km/h): " + speed);
}

/** Requires distance >= 0.0 and time > 0.0 */


private double calcSpeed(double distance, double time) {
assert distance >= 0.0; // (2)

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 53 of 67

assert time >0.0 : "Time is not a positive value: " + time; // (3)
double speed = distance / time;
assert speed >= 0.0; // (4)
return speed;
}
}

Compiling Assertions
# .
8)>3; 4 # # javac
# #

Option -source 1.4

javac # . )+K 3;# -source


1.4 ! '

>javac -source 1.4 Speed.java

# assert #
assert #

public class Legacy {


public static void main(String[] args) {
int assert = 2003;
System.out.println("The year is: " + assert);
}
}

# # '

>javac -source 1.4 Legacy.java


Legacy.java:4: as of release 1.4, assert is a keyword, and may not be used as an
identifier
int assert = 2003;
^
Legacy.java:5: as of release 1.4, assert is a keyword, and may not be used as an
identifier
System.out.println("The year is: " + assert);
^
2 errors

Option -source 1.3

javac 6 -source 1.3


!

H # #

>javac -speed 1.3 Speed.java


Speed.java:14: warning: as of release 1.4, assert is a keyword, and may not be used as an
identifier
assert distance >= 0.0; // (2)
^
Speed.java:15: ';' expected

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 54 of 67

assert distance >= 0.0; // (2)


^
...
9 errors
3 warnings

# * assert (# # # assert
( # # assert #
" # - Legacy
# '

>javac -source 1.3 Legacy.java


Legacy.java:4: as of release 1.4, assert is a keyword, and may not be used as an
identifier
int assert = 2003;
^
Legacy.java:5: as of release 1.4, assert is a keyword, and may not be used as an
identifier
System.out.println("The year is: " + assert);
^
2 warnings
>java Legacy
The year is: 2003

Runtime Enabling and Disabling of Assertions

> #
6

# # java #
# -enableassertions -ea #
disableassertions -da
# 28

# 7 # " # 8
7
-ea 4 !
-da
-ea:<package name>... 4
-da:<package name>...
-ea:... 4 #
-da:...
-ea:<class name> 4
-da:<class name>

Assertion Execution for All Non-system Classes

-ea
4 . 1

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 55 of 67

java.* 4 .
HI

& # .
8)>3;! #
4 %

4 Speed.java # -source 1.4


6 # Speed "
#'

>java -ea Speed


java.lang.AssertionError
at Speed.calcSpeed(Speed.java:14)
at Speed.main(Speed.java:6)
Exception in thread "main"

) 3" 8" > 23? 4


AssertionError # #

4 ! " Speed

>java -da Speed


Speed (km/h): -4.0

( 6 # -ea -da

>java Speed
Speed (km/h): -4.0

(# ! 3" 3" > 23? #


# #

>java -ea Speed


java.lang.AssertionError: Time is not a positive value: -3.0
at Speed.calcSpeed(Speed.java:15)
at Speed.main(Speed.java:7)
Exception in thread "main"

7" #
#
#

Assertion Execution at the Package Level

4 # Trickster
wizard # 1 ;7 38?

# ! #
wizard.pandorasBox wizard.pandorasBox.artifacts
Trickster

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 56 of 67

>java -ea:wizard.pandorasBox... Trickster

... # & !
6

# ! #
Trickster

>java -ea:... Trickster

& #

Assertion Execution at the Class Level

# # Trickster

>java -ea:Trickster Trickster

# #
wizard.pandorasBox.artifacts.Ailment

>java -ea:wizard.pandorasBox.artifacts.Ailment Trickster

4 java # #
#
# # # ! #
# #
wizard.pandorasBox wizard.pandorasBox.artifacts
wizard.pandorasBox.artifacts.Ailment

>java -ea:wizard.pandorasBox... -da:wizard.pandorasBox.artifacts.Ailment Trickster

# # wizard.spells.Baldness

>java -ea Trickster


>java -ea:wizard... Trickster
>java -ea:wizard.spells... Trickster
>java -ea:wizard.spells.Baldness Trickster

( # ) B3 88B"
4 ! #
( #
wizard.pandorasBox.artifacts.Ailment #
wizard.spells.Baldness '

>java -ea -da:wizard.pandorasBox.artifacts.Ailment Trickster

Assertion Execution for All System Classes

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 57 of 67

( # # #
27 >
.
HI ( # # #
# # wizard wizard.pandorasBox
wizard.pandorasBox.artifacts wizard.spells # #
wizard.pandorasBox.artifacts

>java -esa -ea:wizard... -da:wizard.pandorasBox.artifacts... Trickster

# # " # 2 8
9
-enablesystemassertions -esa >
-disablesystemassertions -dsa +

Using Assertions
4 #

#
# # #
# 6

assert reactor.controlCoreTemperature();

4 4
4 F #
# 4 #
AssertionError
4
IllegalArgumentException IndexOutOfBoundsException
NullPointerException.

Internal Invariants

H #
3" status else

int status = ref1.compareTo(ref2);


if (status == 0) {
...
} else if (status > 0) {
...
} else { // (1) status must be negative.
...
}

# 8"

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 58 of 67

int status = ref1.compareTo(ref2);


if (status == 0) {
...
} else if (status > 0) {
...
} else {
assert status < 0 : status; // (2)
...
}

=
4 switch # default
switch case default
# #

switch (trinityMember) {
case Housefather:
...
break;
case THE_SON:
...
break;
case THE_HOLY_GHOST:
...
break;
}

4 default

default:
assert false : trinityMember;

( AssertionError #

A# ! !void case
return # switch

switch (trinityMember) {
case THE_FATHER:
return psalm101;
case THE_SON:
return psalm102;
case THE_HOLY_GHOST:
return psalm103;
default:
assert false: trinityMember;
}
return psalm100; // (3) Compile time error if commented out.

7" # #
!void > # AssertionError assert
default #

default:

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 59 of 67

throw new AssertionError(trinityMember);

Control Flow Invariants

- # #
# #

assert false : "This line should never be reached.";

( #

( #
3"

private void securityMonitor() {


// ...
while (alwaysOnDuty) {
// ...
if (needMaintenance)
return;
// ...
}
// (1) This line should never be reached.
}

3"

- assert
1 while # #
true # assert

Preconditions and Postconditions

1
#

" # 4
1 !

private void adjustReactorThroughput(int increment) {


// Precondition:
assert isValid(increment) : "Throughput increment invalid.";
// Proceed with the adjustment.
// ...
}

) J; 72J" !synchronized
# # *

" L
* 1
adjustReactorThroughPut()
#

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 60 of 67

private void adjustReactorThroughput(int increment) {


// Precondition:
assert isValid(increment) : "Throughput increment invalid.";
// Proceed with the adjustment.
// ...
// Postcondition -- the last action performed before returning.
assert isCoreStable() : "Reactor core not stable.";
}

) ?; 7E8" #

Other Uses

( % % #
'

final static boolean COMPILE_ASSERTS = false;


...
if (COMPILE_ASSERTS)
assert whatEverYouWant; // Not compiled if COMPILE_ASSERTS is false.
...

( %
) <8 773"

static { // Static initializer


boolean assertsAreEnabled = false; // (1)
assert assertsAreEnabled = true; // (2) utilizing side effect
if (!assertsAreEnabled) // (3)
throw new AssertionError("Enable assertions!");
}

3" assertsAreEnabled false ( 8"


assertsAreEnabled true
true 8" true
& # if 7" A # 8"
4 assertsAreEnabled false if 7" #
%
%

Review Questions

$ 4 # # #
@

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 61 of 67

) # #

assert true : true;

# assert true : false;

assert false : true;

" assert false : false;

# @

) # #

-ae

# -enableassertions

-source 1.4

" -disablesystemassertions

-dea

& # @

) #

# FailedAssertion

AssertionException

" RuntimeException

AssertionError

Error

' @

) #

&

# ,

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 62 of 67

" ,

+ G # # # #
@

static int inv(int value) {


assert value > -50 : value < 100;
return 100/value;
}

) # #

inv(-50);

# inv(0);

inv(50);

" inv(100);

inv(150);

, #
org.example.ttp.Bottle@

) # #

-ea

# -ea:Bottle

-ea:org.example

" -ea:org...

-enableexceptions:org.example.ttp.Bottle

-ea:org.example.ttp

- # # #
@

public class TernaryAssertion {


public static void assertBounds(int low, int high, int value) {
assert ( value > low ? value < high : false )
: (value < high ? "too low" : "too high" );
}
public static void main(String[] args) {
assertBounds(100, 200, 150);
}
}

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 63 of 67

) #

assertBounds #
# assert

# assert

" AssertionError # "too


low" #

AssertionError # "too
high" #

AssertionError @

) # #

# ( toString()

( getErrorMessage()

" ( try!catch

AssertionError@

) #

Object

# Throwable

Exception

" Error

RuntimeError

G # # # @

java -ea -da:com... net.example.LaunchTranslator

) # #

com.example.Translator

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 64 of 67

# java.lang.String

dot.com.Boom

" net.example.LaunchTranslator

java.lang.AssertionError

Chapter Summary

# # '

'if if-else switch

'for while do-while

'break continue return

4L(

try!catch!finally #

# # throw

throws

assert

Programming Exercises

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 65 of 67

- # 3EE -
for while do-while" -
while

A # (
Control I .
# )
4

/** A PowerPlant with a reactor core. */


public class PowerPlant {
/** Each power plant has a reactor core. This has package
accessibility so that the Control class that is defined in
the same package can access it. */
Reactor core;

/** Initializes the power plant, creates a reactor core. */


PowerPlant() {
core = new Reactor();
}

/** Sound the alarm to evacuate the power plant. */


public void soundEvacuateAlarm() {
// ... implementation unspecified ...
}

/** Get the level of reactor output that is most desirable at this time.
(Units are unspecified.) */
public int getOptimalThroughput() {
// ... implementation unspecified ...
return 0;
}

/** The main entry point of the program: sets up a PowerPlant


object and a Control object and lets the Control object run the
power plant. */
public static void main(String[] args) {
PowerPlant plant = new PowerPlant();
Control ctrl = new Control(plant);
ctrl.runSystem();
}
}

/** A reactor core that has a throughput that can be either decreased or
increased. */
class Reactor {
/** Get the current throughput of the reactor. (Units are
unspecified.) */
public int getThroughput() {
// ... implementation unspecified ...
return 0;
}

/** @returns true if the reactor status is critical, false otherwise. */


public boolean isCritical() {
// ... implementation unspecified ...

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 66 of 67

return false;
}

/** Ask the reactor to increase throughput. */


void increaseThroughput() throws ReactorCritical {
// ... implementation unspecified ...
}

/** Ask the reactor to decrease throughput. */


void decreaseThroughput() {
// ... implementation unspecified ...
}
}

/** This exception class should be used to report that the reactor status is
critical. */
class ReactorCritical extends Exception {}

/** A controller that will manage the power plant and make sure that the
reactor runs with optimal throughput. */
class Control {
PowerPlant thePlant;

public Control(PowerPlant p) {
thePlant = p;
}

/** Run the power plant by continuously monitoring the


optimalThroughput and the actual throughput of the reactor. If
the throughputs differ by more than 10 units, adjust the reactor
throughput. If the reactor status becomes critical, the evacuate alarm is
sounded and the reactor is shut down.
<p>The runSystem() method can handle the reactor core directly
but calls methods needAdjustment(), adjustThroughput(), and shutdown()
instead. */
public void runSystem() {
// ... provide implementation here ...
}

/** Reports whether the throughput of the reactor needs adjusting.


This method should also monitor and report if the reactor status becomes
critical.
@return true if the optimal and actual throughput values
differ by more than 10 units. */
public boolean needAdjustment() {
// ... provide implementation here ...
}

/** Adjust the throughput of the reactor by calling increaseThroughput() and


decreaseThroughput() methods until the actual throughput is within 10
units of the target throughput. */
public void adjustThroughput(int target) {
// ... provide implementation here ...
}

/** Shut down the reactor by lowering the throughput to 0. */


public void shutdown() {
// ... provide implementation here ...

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006


Page 67 of 67

}
}

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hh40E1.htm 6/16/2006

S-ar putea să vă placă și