do not use break or continue in finally block

Metadata

ID: python-best-practices/finally-no-break-continue-return

Language: Python

Severity: Warning

Category: Best Practices

Description

When using return, break or continue in a finally block, it will stop the spread of any exceptions that were thrown in the try, else, or except blocks and will disregard any return statements.

Learn More

Non-Compliant Code Examples

try:
	client_obj.get_url(url)
except (URLError, ValueError):
	client_obj.remove_url(url)
except SocketTimeout:
	client_obj.handle_url_timeout(url)
finally:
	break  # avoid break in the finally block
try:
	client_obj.get_url(url)
except (URLError, ValueError):
	client_obj.remove_url(url)
except SocketTimeout:
	client_obj.handle_url_timeout(url)
finally:
	return 0  # avoid return in the finally block
try:
	client_obj.get_url(url)
except (URLError, ValueError):
	client_obj.remove_url(url)
except SocketTimeout:
	client_obj.handle_url_timeout(url)
finally:
	continue  # avoid continue in the finally block

Compliant Code Examples

try:
  client_obj.get_url(url)
except (URLError, ValueError):
  client_obj.remove_url(url)
except SocketTimeout:
  client_obj.handle_url_timeout(url)
finally:
  print("cleanup the mess")
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis