Skip to content
Critiq Docs

Search docs

Search documentation pages and rules

correctness.exceptions

Check error before deferring Close

A deferred Close runs even when the open call failed and returned a nil handle.

#Metadata

Rule ID
go.correctness.defer-close-before-check
Severity
high
Confidence
0.85
Languages
go
Presets
strict
Stability
stable
Applies to
block
Tags
correctness, go, rules-catalog

#Why it matters

When `defer file.Close()` runs before the matching `if err != nil` check, a failed open dereferences a nil resource and panics during cleanup.

#Remediation

Return early when the open call sets a non-nil error, then defer the matching `Close()` only once the resource is known to be valid.

#Repository path

The generated metadata points to critiq-rules/libs/rules/catalog/rules/go/go.correctness.defer-close-before-check.rule.yaml.