-
Notifications
You must be signed in to change notification settings - Fork 1
/
chapter10.java
590 lines (491 loc) · 14 KB
/
chapter10.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
// Demonstrate exception handling.
class ExcDemo1 {
public static void main(String[] args) {
int[] nums = new int[4];
try {
System.out.println("Before exception is generated.");
// generate an index out-of-bounds exception
nums[7] = 10;
System.out.println("this won't be displayed");
}
catch (ArrayIndexOutOfBoundsException exc) {
// catch the exception
System.out.println("Index out-of-bounds!");
}
System.out.println("After catch.");
}
}
// -----------------------------------------
/* An exception can be generated by one
method and caught by another. */
class ExcTest {
// Generate an exception.
static void genException() {
int[] nums = new int[4];
System.out.println("Before exception is generated.");
// generate an index out-of-bounds exception
nums[7] = 10;
System.out.println("this won't be displayed");
}
}
class ExcDemo2 {
public static void main(String[] args) {
try {
ExcTest.genException();
} catch (ArrayIndexOutOfBoundsException exc) {
// catch the exception
System.out.println("Index out-of-bounds!");
}
System.out.println("After catch.");
}
}
// -----------------------------------------
// Let JVM handle the error.
class NotHandled {
public static void main(String[] args) {
int[] nums = new int[4];
System.out.println("Before exception is generated.");
// generate an index out-of-bounds exception
nums[7] = 10;
}
}
// -----------------------------------------
// This won't work!
class ExcTypeMismatch {
public static void main(String[] args) {
int[] nums = new int[4];
try {
System.out.println("Before exception is generated.");
//generate an index out-of-bounds exception
nums[7] = 10;
System.out.println("this won't be displayed");
}
/* Can't catch an array boundary error with an
ArithmeticException. */
catch (ArithmeticException exc) {
// catch the exception
System.out.println("Index out-of-bounds!");
}
System.out.println("After catch.");
}
}
// -----------------------------------------
// Handle error and continue.
class ExcDemo3 {
public static void main(String[] args) {
int[] numer = { 4, 8, 16, 32, 64, 128 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
for(int i=0; i<numer.length; i++) {
try {
System.out.println(numer[i] + " / " +
denom[i] + " is " +
numer[i]/denom[i]);
}
catch (ArithmeticException exc) {
// catch the exception
System.out.println("Can't divide by Zero!");
}
}
}
}
// -----------------------------------------
// Use multiple catch clauses.
class ExcDemo4 {
public static void main(String[] args) {
// Here, numer is longer than denom.
int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
for(int i=0; i<numer.length; i++) {
try {
System.out.println(numer[i] + " / " +
denom[i] + " is " +
numer[i]/denom[i]);
}
catch (ArithmeticException exc) {
// catch the exception
System.out.println("Can't divide by Zero!");
}
catch (ArrayIndexOutOfBoundsException exc) {
// catch the exception
System.out.println("No matching element found.");
}
}
}
}
// -----------------------------------------
// Subclasses must precede superclasses in catch clauses.
class ExcDemo5 {
public static void main(String[] args) {
// Here, numer is longer than denom.
int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
for(int i=0; i<numer.length; i++) {
try {
System.out.println(numer[i] + " / " +
denom[i] + " is " +
numer[i]/denom[i]);
}
catch (ArrayIndexOutOfBoundsException exc) {
// catch the exception
System.out.println("No matching element found.");
}
catch (Exception exc) {
System.out.println("Some exception occurred.");
}
}
}
}
// -----------------------------------------
// Use a nested try block.
class NestTrys {
public static void main(String[] args) {
// Here, numer is longer than denom.
int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
try { // outer try
for(int i=0; i<numer.length; i++) {
try { // nested try
System.out.println(numer[i] + " / " +
denom[i] + " is " +
numer[i]/denom[i]);
}
catch (ArithmeticException exc) {
// catch the exception
System.out.println("Can't divide by Zero!");
}
}
}
catch (ArrayIndexOutOfBoundsException exc) {
// catch the exception
System.out.println("No matching element found.");
System.out.println("Fatal error - program terminated.");
}
}
}
// -----------------------------------------
// Manually throw an exception.
class ThrowDemo {
public static void main(String[] args) {
try {
System.out.println("Before throw.");
throw new ArithmeticException();
}
catch (ArithmeticException exc) {
// catch the exception
System.out.println("Exception caught.");
}
System.out.println("After try/catch block.");
}
}
// -----------------------------------------
// Rethrow an exception.
class Rethrow {
public static void genException() {
// here, numer is longer than denom
int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
for(int i=0; i<numer.length; i++) {
try {
System.out.println(numer[i] + " / " +
denom[i] + " is " +
numer[i]/denom[i]);
}
catch (ArithmeticException exc) {
// catch the exception
System.out.println("Can't divide by Zero!");
}
catch (ArrayIndexOutOfBoundsException exc) {
// catch the exception
System.out.println("No matching element found.");
throw exc; // rethrow the exception
}
}
}
}
class RethrowDemo {
public static void main(String[] args) {
try {
Rethrow.genException();
}
catch(ArrayIndexOutOfBoundsException exc) {
// recatch exception
System.out.println("Fatal error - " +
"program terminated.");
}
}
}
// -----------------------------------------
// Using two Throwable methods.
class ExcTest {
static void genException() {
int[] nums = new int[4];
System.out.println("Before exception is generated.");
// generate an index out-of-bounds exception
nums[7] = 10;
System.out.println("this won't be displayed");
}
}
class UseThrowableMethods {
public static void main(String[] args) {
try {
ExcTest.genException();
}
catch (ArrayIndexOutOfBoundsException exc) {
// catch the exception
System.out.println("Standard message is: ");
System.out.println(exc);
System.out.println("\nStack trace: ");
exc.printStackTrace();
}
System.out.println("After catch.");
}
}
// -----------------------------------------
// Use finally.
class UseFinally {
public static void genException(int what) {
int t;
int[] nums = new int[2];
System.out.println("Receiving " + what);
try {
switch(what) {
case 0:
t = 10 / what; // generate div-by-zero error
break;
case 1:
nums[4] = 4; // generate array index error.
break;
case 2:
return; // return from try block
}
}
catch (ArithmeticException exc) {
// catch the exception
System.out.println("Can't divide by Zero!");
return; // return from catch
}
catch (ArrayIndexOutOfBoundsException exc) {
// catch the exception
System.out.println("No matching element found.");
}
finally {
System.out.println("Leaving try.");
}
}
}
class FinallyDemo {
public static void main(String[] args) {
for(int i=0; i < 3; i++) {
UseFinally.genException(i);
System.out.println();
}
}
}
// -----------------------------------------
// Use throws.
class ThrowsDemo {
public static char prompt(String str)
throws java.io.IOException {
System.out.print(str + ": ");
return (char) System.in.read();
}
public static void main(String[] args) {
char ch;
try {
ch = prompt("Enter a letter");
}
catch(java.io.IOException exc) {
System.out.println("I/O exception occurred.");
ch = 'X';
}
System.out.println("You pressed " + ch);
}
}
// -----------------------------------------
// Use the multi-catch feature. Note: This code requires JDK 7 or
// later to compile.
class MultiCatch {
public static void main(String[] args) {
int a=88, b=0;
int result;
char[] chrs = { 'A', 'B', 'C' };
for(int i=0; i < 2; i++) {
try {
if(i == 0)
result = a / b; // generate an ArithmeticException
else
chrs[5] = 'X'; // generate an ArrayIndexOutOfBoundsException
// This catch clause catches both exceptions.
}
catch(ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: " + e);
}
}
System.out.println("After multi-catch.");
}
}
// -----------------------------------------
// Use a custom exception.
// Create an exception.
class NonIntResultException extends Exception {
int n;
int d;
NonIntResultException(int i, int j) {
super("Result is not an integer.");
n = i;
d = j;
}
public String toString() {
return "Result of " + n + " / " + d +
" is non-integer.";
}
}
class CustomExceptDemo {
public static void main(String[] args) {
// Here, numer contains some odd values.
int[] numer = { 4, 8, 15, 32, 64, 127, 256, 512 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
for(int i=0; i<numer.length; i++) {
try {
if((numer[i]%denom[i]) != 0)
throw new
NonIntResultException(numer[i], denom[i]);
System.out.println(numer[i] + " / " +
denom[i] + " is " +
numer[i]/denom[i]);
}
catch (ArithmeticException exc) {
// catch the exception
System.out.println("Can't divide by Zero!");
}
catch (ArrayIndexOutOfBoundsException exc) {
// catch the exception
System.out.println("No matching element found.");
}
catch (NonIntResultException exc) {
System.out.println(exc);
}
}
}
}
// -----------------------------------------
/*
Try This 10-1
Add exception handling to the stack classes.
*/
// An exception for stack-full errors.
class StackFullException extends Exception {
int size;
StackFullException(int s) {
super("Stack Full");
size = s;
}
public String toString() {
return "\nStack is full. Maximum size is " + size;
}
}
// An exception for stack-empty errors.
class StackEmptyException extends Exception {
StackEmptyException() {
super("Stack Empty");
}
public String toString() {
return "\nStack is empty.";
}
}
// A fixed-length stack for characters that uses exceptions.
class FixedLengthStack implements ISimpleStack {
private char[] data; // this array holds the stack
private int tos; // index of top of stack
// Construct an empty stack given its size.
FixedLengthStack(int size) {
data = new char[size]; // create the array to hold the stack
tos = 0;
}
// Construct a stack from a stack.
FixedLengthStack(FixedLengthStack otherStack) {
// size of new stack equals that of otherStack
data = new char[otherStack.data.length];
// set tos to the same position
tos = otherStack.tos;
// copy the contents
for(int i = 0; i < tos; i++)
data[i] = otherStack.data[i];
}
// Construct a stack with initial values.
FixedLengthStack(char[] chrs) throws StackFullException {
// create the array to hold the initial values
data = new char[chrs.length];
tos = 0;
// initialize the stack by pushing the contents
// of chrs onto it
for(char ch : chrs)
push(ch);
}
// Push a character onto the stack.
public void push(char ch) throws StackFullException {
if(isFull())
throw new StackFullException(data.length);
data[tos] = ch;
tos++;
}
// Pop a character from the stack.
public char pop() throws StackEmptyException {
if(isEmpty())
throw new StackEmptyException();
tos--;
return data[tos];
}
// Return true if the stack is empty.
public boolean isEmpty() {
return tos==0;
}
// Return true if the stack is full.
public boolean isFull() {
return tos==data.length;
}
}
// A simple stack interface that throws exceptions.
public interface ISimpleStack {
// Push a character onto the stack.
void push(char ch) throws StackFullException;
// Pop a character from the stack.
char pop() throws StackEmptyException;
// Return true if the stack is empty.
boolean isEmpty();
// Return true if the stack is full.
boolean isFull();
}
// Demonstrate the stack exceptions.
class SimpleStackExcDemo {
public static void main(String[] args) {
FixedLengthStack stack = new FixedLengthStack(5);
char ch;
int i;
try {
// overrun the stack
for(i=0; i < 6; i++) {
System.out.print("Attempting to push : " +
(char) ('A' + i));
stack.push((char) ('A' + i));
System.out.println(" - OK");
}
System.out.println();
}
catch (StackFullException exc) {
System.out.println(exc);
}
System.out.println();
try {
// over-empty the stack
for(i=0; i < 6; i++) {
System.out.print("Popping next char: ");
ch = stack.pop();
System.out.println(ch);
}
}
catch (StackEmptyException exc) {
System.out.println(exc);
}
}
}