Java Reference
In-Depth Information
public void m1() throws Exception1, Exception3 {
statement-1; // May throw Exception1
try {
statement-2; // May throw Exception2
}
catch(Exception2 e){
// Handle Exception2 here
}
statement-3; // May throw Exception3
}
Let's get back to the
ReadInput
class example. Listing 9-3 fixed the compiler error by adding a
try-catch
block.
Let's now use the second option: include a
throws
clause in the
readChar()
method's declaration. Listing 9-5 has
another version of the
ReadInput
class, which is called
ReadInput2
.
Listing 9-5.
Using a throws Clause in a Method's Declaration
// ReadInput2.java
package com.jdojo.exception;
import java.io.IOException;
public class ReadInput2 {
public static char readChar()
throws IOException
{
char c = '\u0000';
int input = 0;
input = System.in.read();
if (input != -1) {
c = (char)input;
}
return c;
}
}
The following code for the
ReadInput2Test
class tests the
readChar()
method of the
ReadInput2
class:
// ReadInput2Test.java
package com.jdojo.exception;
public class ReadInput2Test {
public static void main(String[] args) {
System.out.print("Enter some text and then press Enter key: ");
char c = ReadInput2.readChar();
System.out.print("The first character you entered is: " + c);
}
}
Now, compile the
ReadInput2Test
class. Oops! Compiling the
ReadInput2Test
class generates the following error:
Error(6,11): unreported exception: class java.io.IOException; must be caught or declared to be thrown