Here's an example from the book "Java All-in-one desk reference"
public class CrazyWithZeros {
public static void main(String[] args) {
try {
int answer = divideTheseNumbers(5, 0);
} catch (Exception e) {
System.out.println("Tried twice, still didn't work!");
}
}
public static int divideTheseNumbers(int a, int b) throws Exception {
int c;
try {
c = a / b;
System.out.println("It worked!");
} catch (Exception e) {
System.out.println("Didn't work the first time.");
c = a / b;
System.out.println("It worked the second time!");
} finally {
System.out.println("Better clean up my mess.");
}
System.out.println("It worked after all.");
return c;
}
}
After the finally clause executes, the ArithmeticException is thrown back up to the calling method. The statement System.out.println("It worked after all.");
would never be executed in this case. But what happened to the return c;
?
I wonder whether the return statement would still return the result of the division or not?
========
I tried to replace "System.out.println("Better clean up my mess.");
" with "System.out.println(c);
", then it's compiled and the results are as follows:
Didn't work the first time. 0 Tried twice, still didn't work!
I can't believe the variable c
could be calculated. (it's the wrong number, though) Why could this happen?
Then I also tried to replace "System.out.println("Better clean up my mess.");
" with "return c;
" and deleted the statements below the finally block, it's compiled again...Since the finally block is executed whether or not any exceptions are thrown by the try block or caught by any catch blocks, the return c; should be executed. But here're the results:
Didn't work the first time.
looks like c
couldn't get returned...