-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChapter9.lst
More file actions
533 lines (459 loc) · 13.1 KB
/
Copy pathChapter9.lst
File metadata and controls
533 lines (459 loc) · 13.1 KB
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
listing 1
// 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 statement.");
}
}
listing 2
/* 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 statement.");
}
}
listing 3
// 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;
}
}
listing 4
// 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 statement.");
}
}
listing 5
// Handle error gracefully 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!");
}
}
}
}
listing 6
// Use multiple catch statements.
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.");
}
}
}
}
listing 7
// Subclasses must precede superclasses in catch statements.
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 (Throwable exc) {
System.out.println("Some exception occurred.");
}
}
}
}
listing 8
// 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.");
}
}
}
listing 9
// 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.");
}
}
listing 10
// 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.");
}
}
}
listing 11
// Using the 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 statement.");
}
}
listing 12
// 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();
}
}
}
listing 13
// 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);
}
}
listing 14
// Use the multi-catch feature. Note: This code requires JDK 7 or
// later to compiler.
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.");
}
}
listing 15
// Use a custom exception.
// Create an exception.
class NonIntResultException extends Exception {
int n;
int d;
NonIntResultException(int i, int j) {
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]%2) != 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);
}
}
}
}
listing 16
// An exception for queue-full errors.
public class QueueFullException extends Exception {
int size;
QueueFullException(int s) { size = s; }
public String toString() {
return "\nQueue is full. Maximum size is " +
size;
}
}
listing 17
// An exception for queue-empty errors.
public class QueueEmptyException extends Exception {
public String toString() {
return "\nQueue is empty.";
}
}
listing 18
/*
Try This 9-1
Add exception handling to the queue classes.
*/
// A fixed-size queue class for characters that uses exceptions.
class FixedQueue implements ICharQ {
private char q[]; // this array holds the queue
private int putloc, getloc; // the put and get indices
// Construct an empty queue given its size.
public FixedQueue(int size) {
q = new char[size]; // allocate memory for queue
putloc = getloc = 0;
}
// Put a characer into the queue.
public void put(char ch)
throws QueueFullException {
if(putloc==q.length)
throw new QueueFullException(q.length);
q[putloc++] = ch;
}
// Get a character from the queue.
public char get()
throws QueueEmptyException {
if(getloc == putloc)
throw new QueueEmptyException();
return q[getloc++];
}
}
listing 19
// Demonstrate the queue exceptions.
class QExcDemo {
public static void main(String args[]) {
FixedQueue q = new FixedQueue(10);
char ch;
int i;
try {
// overrun the queue
for(i=0; i < 11; i++) {
System.out.print("Attempting to store : " +
(char) ('A' + i));
q.put((char) ('A' + i));
System.out.println(" -- OK");
}
System.out.println();
}
catch (QueueFullException exc) {
System.out.println(exc);
}
System.out.println();
try {
// over-empty the queue
for(i=0; i < 11; i++) {
System.out.print("Getting next char: ");
ch = q.get();
System.out.println(ch);
}
}
catch (QueueEmptyException exc) {
System.out.println(exc);
}
}
}
listing 20
// A character queue interface that throws exceptions.
public interface ICharQ {
// Put a characer into the queue.
void put(char ch) throws QueueFullException;
// Get a character from the queue.
char get() throws QueueEmptyException;
}