Java Reference
In-Depth Information
Enter some text and press Enter key: Hello
First character you entered is: H
Checked Exception - Catch or Declare
If a piece of code may throw a checked exception, you must do one of the following:
try-catch block.
Handle the checked exception by placing the piece of code inside a
The call to the System.in.read() method in the readChar() method of the ReadInput class (see Listing 9-3)
throws a checked exception of the IOException type. You applied the first option in this case and handled the
IOException by placing the call to the System.in.read() method in a try-catch block
Let's assume that you are writing a method m1() for a class that has three statements. Suppose three statements
may throw checked exceptions of types Exception1 , Exception2 , and Exception3 , respectively.
Specify in your method/constructor declaration that it throws the checked exception.
// Will not compile
public void m1() {
statement-1; // May throw Exception1
statement-2; // May throw Exception2
statement-3; // May throw Exception3
}
You cannot compile the code for the m1() method in the above form. You must either handle the exception using
a try-catch block or include in its declaration that it may throw the three checked exceptions. If you want to handle
the checked exceptions in the m1() method's body, your code may look as follows:
public void m1() {
try {
statement-1; // May throw Exception1
statement-2; // May throw Exception2
statement-3; // May throw Exception3
}
catch(Exception1 e1) {
// Handle Exception1 here
}
catch(Exception2 e2) {
// Handle Exception2 here
}
catch(Exception3 e3) {
// Handle Exception3 here
}
}
The above code assumes that when one of the three exceptions is thrown, you do not want to execute the
remaining statements.
 
Search WWH ::




Custom Search