fix or disallow 'break' and 'continue' in 'finally'
See original GitHub issuebreak
(and likely continue
) in finally
can create confusing definite initialization scenarios that aren’t properly handled by the type checker.
It may make sense to disallow them (and return
too, for good measure?)
Here’s an example where break
is used to “skip past” a return
statement, which confuses the type checker:
shared void run() {
String s;
while (true) {
try {
if (1==2) {
s = "hello";
break; // if the type checker were smarter, we could comment out this line
} else {
return;
}
} finally {
break; // skips over the "return" in "else" above
}
}
print(s); // prints "<null>"! (or on the JVM, a backend error)
}
Issue Analytics
- State:
- Created 6 years ago
- Comments:5 (5 by maintainers)
Top Results From Across the Web
Why is `continue` not allowed in a `finally` clause in Python?
The use of continue in a finally-clause is forbidden because its interpretation would have been problematic.
Read more >Python "finally" Statement: An Ultimate Guide (with Examples)
Break with “finally” Statement The break statement exits a loop in Python. If you do error handling in a loop and you break...
Read more >Never exit a finally block with a return, break, continue, or throw
Rule Definition Care must be taken if completion of a try-catch block occurs as a result of executing a return. If a finally...
Read more >PEP 601: Forbid return/break/continue breaking out of finally
Using return , break or continue in a finally clause is probably inadvisable, but forbidding them seems unnecessary and unhelpful to me.
Read more >ERR04-J. Do not complete abruptly from a finally block
Never use return , break , continue , or throw statements within a finally block. When program execution enters a try block that...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I believe
throw
should always be allowed without warning (and, it’s unrelated to the initialization issue, and exceptions can occur in any code anyway), but otherwise that sounds reasonable to me.@jvasileff so I’ve done two things:
break
infinally
, so at least the two cases you provided are correctly detected as errors by the typechecker.finally
block. This seems reasonable to me:finally
blocks definitely aren’t for doingbreak
/return
/continue
. However, I’m not certain aboutthrow
. I’ve certainly seen peoplethrow
fromfinally
, and, though I don’t like it, perhaps you need to sometimes?WDYT? Is this a good solution?