Details
-
Bug
-
Status: Closed
-
Major
-
Resolution: Fixed
-
None
-
None
-
None
Description
The following code was written for a "Groovy puzzlers" talk:
class CountDown { int counter = 10 } CountDown finalCountDown() { def countDown = new CountDown() try { countDown.counter = --countDown.counter } catch (ignored) { println "That will never happen. ${ignored.message}" countDown.counter = Integer.MIN_VALUE } finally { return countDown } } println finalCountDown().counter
At execution, it goes to the catch because of a class cast exception:
"Cannot cast object '9' with class 'java.lang.Integer' to class 'CountDown'"
The reason is highlighted after returns have been added:
java.lang.Object countDown = new CountDown() try { return countDown .counter = --( countDown .counter) } catch (java.lang.Exception ignored) { this.println("That will never happen. $ignored.message") return countDown .counter = java.lang.Integer.MIN_VALUE } finally { return countDown }
A "return" is added to the try branch, even though there's a return in the finally block which should always be executed. Adding a single statement after the finally block solves the issue because no return would then be added to the try block...