The Artima Developer Community
Sponsored Link

Interface Design by Bill Venners
Throw exceptions on abnormal conditions

Advertisement

Interface Design | Contents | Previous | Next

This is in deciding your contract. You shouldn't promise to do something unless the chances are you'll be able to do it most of the time.

Abnormal Conditions


Example: FileInputStream

 1 // In file ex9/Example9a.java
 2 import java.io.*;
 3 class Example9a {
 4
 5     public static void main(String[] args)
 6         throws IOException {
 7
 8         if (args.length == 0) {
 9             System.out.println("Must give filename as first arg.");
10             return;
11         }
12
13         FileInputStream in;
14         try {
15             in = new FileInputStream(args[0]);
16         }
17         catch (FileNotFoundException e) {
18             System.out.println("Can't find file: " + args[0]);
19             return;
20         }
21
22         int ch;
23         while ((ch = in.read()) != -1) {
24             System.out.print((char) ch);
25         }
26         System.out.println();
27
28         in.close();
29     }
30

Example: StringTokenizer and Stack

 1 // In file ex9/Example9c.java
 2 // This program prints the white-space separated tokens of an
 3 // ASCII file in reverse order of their appearance in the file.
 4 import java.io.*;
 5 import java.util.*;
 6 class Example9c {
 7
 8     public static void main(String[] args)
 9         throws IOException {
10
11         if (args.length == 0) {
12             System.out.println("Must give filename as first arg.");
13             return;
14         }
15
16         FileInputStream in = null;
17         try {
18             in = new FileInputStream(args[0]);
19         }
20         catch (FileNotFoundException e) {
21             System.out.println("Can't find file: " + args[0]);
22             return;
23         }
24
25         // Read file into a StringBuffer
26         StringBuffer buf = new StringBuffer();
27         try {
28             int ch;
29             while ((ch = in.read()) != -1) {
30                 buf.append((char) ch);
31             }
32         }
33         finally {
34             in.close();
35         }
36
37         // Separate StringBuffer into tokens and
38         // push each token into a Stack
39         StringTokenizer tok = new StringTokenizer(buf.toString());
40         Stack stack = new Stack();
41         while (tok.hasMoreTokens()) {
42             stack.push(tok.nextToken());
43         }
44
45         // Print out tokens in reverse order.
46         while (!stack.empty()) {
47             System.out.println((String) stack.pop());
48         }
49     }
50

Why Just Abnormal Conditions?


Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2017 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us