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