If using generic exception, it should be last

このページは日本語には対応しておりません。随時翻訳に取り組んでいます。
翻訳に関してご質問やご意見ございましたら、お気軽にご連絡ください

Metadata

ID: python-best-practices/generic-exception-last

Language: Python

Severity: Notice

Category: Best Practices

Description

When multiple exceptions are caught, the generic Exception must be caught last. Catching Exception is very generic and if placed before specific exceptions, it will caught all exceptions and specific exception handlers will not be caught.

For this reason, generic Exception must be the last to be handled to let specific exception handlers to be triggered/executed.

Learn More

Non-Compliant Code Examples

try:
	pass
except Exception:
	pass
except FileNotFound as e:
	pass

Compliant Code Examples

try:
	pass
except MyError:
	pass
except Exception as e:
	pass
try:
	pass
except MyError:
	pass
except FileNotFound as e:
	pass
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