@@ -49,6 +49,73 @@ public void finallyWithoutCatch() {
4949 assertEquals (s ,__ );
5050 }
5151
52+ private int k = 1 , m = 2 ;
53+
54+ private void tryCatchFinallyWithVoidReturn () {
55+ try {
56+ doStuff ();
57+ } catch (IOException e ) {
58+ k += 1 ;
59+ return ;
60+ } finally {
61+ // Will this code be executed despite the return statement above?
62+ k += 1 ;
63+ }
64+ }
65+
66+ @ Koan
67+ public void finallyIsAlwaysRan () {
68+ tryCatchFinallyWithVoidReturn ();
69+ assertEquals (k ,3 );
70+ }
71+
72+ private int tryCatchFinallyReturningInt () {
73+ try {
74+ doStuff ();
75+ } catch (IOException e ) {
76+ k += 1 ;
77+ return k + m ;
78+ } finally {
79+ m = 5 ;
80+ }
81+ return k ;
82+ }
83+
84+ @ Koan
85+ public void orderOfCatchFinallyAndReturn () {
86+ k = 1 ;
87+ assertEquals (tryCatchFinallyReturningInt (),4 );
88+ // What is the order of executing catch, finally
89+ // and return statements in this case?
90+ assertEquals (k ,2 );
91+ assertEquals (m ,5 );
92+ }
93+
94+ private int i = 0 , j = 1 , l = 2 ;
95+
96+ private int returnStatementsEverywhere () {
97+ try {
98+ doStuff ();
99+ return i ++;
100+ } catch (IOException e ) {
101+ return j ++;
102+ } finally {
103+ // Watch out! It is an EXTREMELY bad practice to
104+ // put return statement in finally block!
105+ return l ++;
106+ }
107+ }
108+
109+ @ Koan
110+ public void returnInFinallyBlock () {
111+ // Which value will be returned here?
112+ assertEquals (returnStatementsEverywhere (),2 );
113+ // Is only the returned variable modified?
114+ assertEquals (i ,__ );
115+ assertEquals (j ,__ );
116+ assertEquals (l ,__ );
117+ }
118+
52119 private void doUncheckedStuff () {
53120 throw new RuntimeException ();
54121 }
0 commit comments