Java Reference
In-Depth Information
TRY IT OUT: A Loop Block That Is a try Block
You can make j a loop control variable and count down so that eventually you get a zero divisor in the
loop:
public class TestLoopTryCatch {
public static void main(String[] args) {
int i = 12;
for(int j=3 ; j > =-1 ; --j) {
try {
System.out.println("Try block entered i = " + i + " j = " +
j);
System.out.println(i/j);
// Divide by 0 -
exception thrown
System.out.println("Ending try block");
} catch(ArithmeticException e) { // Catch the exception
System.out.println("Arithmetic exception caught: " + e);
}
}
System.out.println("After try block");
}
}
TestLoopTryCatch.java
This produces the following output:
Try block entered i = 12 j = 3
4
Ending try block
Try block entered i = 12 j = 2
6
Ending try block
Try block entered i = 12 j = 1
12
Ending try block
Try block entered i = 12 j = 0
Arithmetic exception caught: java.lang.ArithmeticException: / by zero
Try block entered i = 12 j = -1
-12
Ending try block
After try block
How It Works
Search WWH ::




Custom Search