Java Reference
In-Depth Information
If you want to use different logic, you might need more than one try-catch block. For example, if your logic
states that you must attempt to execute all three statements, even if the previous statement throws an exception, your
code would look as follows:
public void m1() {
try {
statement-1; // May throw Exception1
}
catch(Exception1 e1) {
// Handle Exception1 here
}
try {
statement-2; // May throw Exception2
}
catch(Exception2 e2) {
// Handle Exception2 here
}
try {
statement-3; // May throw Exception3
}
catch(Exception3 e3) {
// Handle Exception3 here
}
}
The second way to get rid of the compiler error is to specify in the m1() method's declaration that it throws three
checked exceptions. This is accomplished by using a throws clause in the m1() method's declaration. The general
syntax for a throws clause is
<<modifiers>> <<return type>> <<method name>>(<<params>>) throws <<List of Exceptions>> {
// Method body goes here
}
The keyword throws is used to specify a throws clause. The throws clause is placed after the closing parenthesis
of the method's parameters list. The throws keyword is followed by a comma-separated list of exception types. Recall
that an exception type is nothing but the name of a Java class, which is in the exception class hierarchy. You can
specify a throws clause in the declaration of the m1() method as follows:
public void m1() throws Exception1, Exception2, Exception3 {
statement-1; // May throw Exception1
statement-2; // May throw Exception2
statement-3; // May throw Exception3
}
You can also mix the two options in the same method when a piece of code throws more than one checked
exception. You can handle some of them using a try-catch block, and declare some of them using a throws clause in
method's declaration. The following code handles Exception2 using a try-catch block and uses a throws clause to
declare exceptions Exception1 and Exception3 :
 
Search WWH ::




Custom Search