Java Reference
In-Depth Information
All exceptions that are not checked exceptions are called unchecked exceptions. The
Error
class, all subclasses
of the
Error
class, the
RuntimeException
class, and all its subclasses are unchecked exceptions. They are called
unchecked exceptions because the compiler does not check if they are handled in the code. However, you are free to
handle them. The program structure for handling a checked or an unchecked exception is the same. The difference
between them is in the way the compiler forces (or does not force) you to handle them in the code.
Let's fix the compiler error for the
ReadInput
class. Now you know that
java.io.IOException
is a checked
exception and the compiler will force you to handle it. You will handle it by using a
try-catch
block. Listing 9-3 shows
the code for the
ReadInput
class. This time, you have handled the
IOException
in its
readChar()
method and the code
will compile fine.
Listing 9-3.
A ReadInput Class Whose readChar() Method Reads One Character from the Standard Input
// ReadInput.java
package com.jdojo.exception;
import java.io.IOException;
public class ReadInput {
public static char readChar() {
char c = '\u0000';
int input = 0;
try {
input = System.in.read();
if (input != -1) {
c = (char)input;
}
}
catch (IOException e) {
System.out.print("IOException occurred while reading input.");
}
return c;
}
}
How do you use the
ReadInput
class? You can use it the same way you use other classes in Java. You need to call
the
ReadInput.readChar() static
method if you want to capture the first character entered by the user. Listing 9-4
has code that shows how to use the
ReadInput
class. It prompts the user to enter some text. The first character of the
entered text is shown on the standard output.
Listing 9-4.
A Program to Test the ReadInput Class
// ReadInputTest.java
package com.jdojo.exception;
public class ReadInputTest {
public static void main(String[] args) {
System.out.print("Enter some text and press Enter key: ");
char c = ReadInput.readChar();
System.out.println("First character you entered is: " + c);
}
}