Java Reference
In-Depth Information
The compiler error may not be very clear to you at this point. The readChar() method of the ReadInput2 class
declares that it may throw an IOException . The IOException is a checked exception. Therefore, the following piece of
code in the main() method of ReadInput2Test may throw a checked IOException :
char c = ReadInput2.readChar();
Recall the rules about handling the checked exceptions, which I mentioned in the beginning of this section. If a
piece of code may throw a checked exception, you must use one of the two options: place that piece of code inside a
try-catch block to handle the exception, or specify the checked exception using a throws clause in the method's or
constructor's declaration. Now, you must apply one of the two options for the ReadInput2.readChar() method's call
in the main() method. Listing 9-6 uses the first option and places the call to ReadInput2.readChar() method inside a
try-catch block. Note that you have placed three statements inside the try block, which is not necessary. You needed
to place inside the try block only the code that may throw the checked exception.
Listing 9-6. A Program to Test the ReadInput2.readChar() Method
// ReadInput2Test2.java
package com.jdojo.exception;
import java.io.IOException;
public class ReadInput2Test2 {
public static void main(String[] args) {
char c = '\u0000';
try {
System.out.print("Enter some text and then press Enter key:");
c = ReadInput2.readChar();
System.out.println("The first character you entered is: " + c);
}
catch(IOException e) {
System.out.println("Error occurred while reading input.");
}
}
}
You can also use the second option to fix the compiler error. Listing 9-7 has the code using the second option.
Listing 9-7. A Program to Test the ReadInput2.readChar() Method
// ReadInput2Test3.java
package com.jdojo.exception;
import java.io.IOException;
public class ReadInput2Test3 {
public static void main(String[] args) throws IOException {
char c = '\u0000';
System.out.print("Enter some text and then press Enter key: ");
c = ReadInput2.readChar();
System.out.print("The first character you entered is: " + c);
}
}
 
Search WWH ::




Custom Search