[issue21067] Support Multiple finally clauses.

Kevin Cox report at bugs.python.org
Tue Mar 25 23:44:17 CET 2014


New submission from Kevin Cox:

I think it would be useful to support multiple finally clauses.  The idea would be that each clause would be run, even if prior clauses throw exceptions.

The idea came when hunting a bug in the Mozilla test suite.  The code looked like as follows.

try:
	resource1 = allocateresource1()
	resource2 = allocateresource2()
	
	dostuffthatmightthrowexception()
finally:
	if resource1:
		resource1.close()
	if resource2:
		resource2.close()

The problem is that if resource1,close() throws an exception resource2 is not closed.

The alternative looks like this.

try:
	resource1 = allocateresource1()
	try:
		resource2 = allocateresource2()
		
		dostuffthatmightthrowexception()
	finally:
		if resource2:
			resource2.close()
finally:
	if resource2:
		resource2.close()

Or it could look like this.

try:
	resource1 = allocateresource1()
	resource2 = allocateresource2()
	
	dostuffthatmightthrowexception()
finally:
	try:
		if resource1:
			resource1.close()
	finally:
		if resource2:
			resource2.close()

Both of which exhibit indentation explosion when there are a number of resources that need to be cleaned up.

If multiple finally clauses were allowed the code would be much more readable and would look as follows.

try:
	resource1 = allocateresource1()
	resource2 = allocateresource2()
	
	dostuffthatmightthrowexception()
finally:
	if resource1:
		resource1.close()
finally:
	if resource2:
		resource2.close()

----------
messages: 214861
nosy: kevincox
priority: normal
severity: normal
status: open
title: Support Multiple finally clauses.

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue21067>
_______________________________________


More information about the Python-bugs-list mailing list