Chapter 11: Input/Output and Exception Handling
Reading Text Files
- Scanner in = new Scanner (new FileReader ("input.txt"));
Writing Text Files
- PrintWriter out = new PrintWriter("output.txt");
Closing Files
Exceptions
- Figure 1 on page 434 shows an inheritance hierarchy of exception classes.
- If you want to report an exception, use the throw command
- throw new IllegalArgumentException();
- Unchecked exceptions extend the RuntimeException class or Error class.
Unchecked exceptions arise due to programmer error.
For example, dividing by 0.
- Checked exceptions are everything else in the Figure 1 inheritance
hierarchy. Checked exceptions are due to external circumstances
that the programmer cannot prevent. For example, the program is
reading information across the internet and the network connection
goes down.
- To show that a method can throw an Exception use the
throws command
- public void read (String filename) throws FileNotFoundException { ... }
Lecture Code
Note: For the code below to work, a file named lab10.htm must
exist in the same directory as Demo.java.