do not use break or continue in finally block

Cette page n'est pas encore disponible en français, sa traduction est en cours.
Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.

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