do not use bare except

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/no-bare-except

Language: Python

Severity: Warning

Category: Best Practices

Description

Avoid bare except. Try to always use specialized exception names in except blocks.

Non-Compliant Code Examples

try:
  print("foo")
except:  # use a specialized exception name
  print("bar")

Compliant Code Examples

try:
    parsed = json.loads(response.body)
except json.JSONDecodeError:
    log.warning("Test skips request responded with invalid JSON '%s'", response.body)
    return
try:
  pass
except (TypeError, ValueError):
    log.debug(
        (
            "received invalid x-datadog-* headers, "
            "trace-id: %r, parent-id: %r, priority: %r, origin: %r, tags:%r"
        ),
        trace_id,
        parent_span_id,
        sampling_priority,
        origin,
        tags_value,
    )
try:
    foo()
except MyError as e:
    bar()
try:
  print("foo")
except MyException:
  print("bar")
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

PREVIEWING: esther/docs-9518-update-example-control-sensitive-log-data