If using generic exception, it should be last

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/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