Python
warnings
exceptions
error handling
programming

In Python, how does one catch warnings as if they were exceptions?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Python warnings are designed as non-fatal signals: they inform you about deprecated APIs, numerical issues, or suspicious behavior without stopping execution. In testing, CI, and strict production checks, this default can be too permissive. If a warning indicates unsafe behavior, you may want it to fail immediately like an exception.

Python’s warnings module supports this directly. You can elevate specific warning categories to errors globally, per module, or within a temporary context. The key is scoping the rule correctly so you enforce quality without breaking unrelated code paths.

Core Sections

1. Convert warnings to exceptions in a local context

Use warnings.catch_warnings() and set a filter to "error".

python
1import warnings
2
3def old_api():
4    warnings.warn("old_api is deprecated", DeprecationWarning)
5
6try:
7    with warnings.catch_warnings():
8        warnings.simplefilter("error", DeprecationWarning)
9        old_api()
10except DeprecationWarning as exc:
11    print("Caught as exception:", exc)

This approach is ideal for unit tests because it limits behavior change to a precise block.

2. Configure process-wide behavior for test runs

You can make warnings fatal for the whole Python process using CLI flags or environment variables.

bash
python -W error::DeprecationWarning -m pytest

Or in code at startup:

python
import warnings
warnings.filterwarnings("error", category=RuntimeWarning)

For pytest projects, keep this in pytest.ini for consistent team behavior:

ini
1[pytest]
2filterwarnings =
3    error::DeprecationWarning
4    error::RuntimeWarning

This catches issues early and prevents warning accumulation from becoming technical debt.

3. Capture and inspect warnings when you do not want hard failure

Sometimes you need to assert warnings occurred, not fail on them.

python
1import warnings
2
3with warnings.catch_warnings(record=True) as captured:
4    warnings.simplefilter("always")
5    warnings.warn("possible precision loss", UserWarning)
6
7assert len(captured) == 1
8assert "precision loss" in str(captured[0].message)

This is useful for validating public API behavior where warning emission is expected and documented.

For libraries, avoid setting global warning policy at import time. Let applications decide strictness.

Common Pitfalls

  • Using broad error filters globally and unintentionally failing on third-party warnings outside your control.
  • Filtering the wrong category (for example UserWarning instead of DeprecationWarning) and missing the intended signal.
  • Forgetting that some warning categories are ignored by default unless explicitly enabled.
  • Setting warning policy in library import code, which surprises downstream users and test environments.
  • Catching Exception around warning-to-error blocks and accidentally suppressing the signal you meant to enforce.

Summary

To catch warnings as exceptions in Python, elevate specific warning categories using warnings.simplefilter("error", ...) in scoped contexts or test configuration. Use global policies in CI carefully, and prefer targeted categories to avoid noisy failures. This pattern turns soft signals into enforceable quality gates while keeping behavior explicit and maintainable.

In larger codebases, warning policy works best when organized by risk level. For example, treat deprecations in your own package as errors, but initially keep third-party deprecations as visible warnings until dependency upgrades are planned. This phased model avoids alert fatigue while still enforcing internal quality standards. Over time, promote more categories to errors as the codebase stabilizes.

You can also combine warning enforcement with test markers. Critical paths (numerical kernels, security-sensitive parsing, data validators) can run under stricter filters than low-risk utilities. This targeted enforcement improves signal quality and keeps CI actionable. The goal is not to fail on every warning forever; it is to make warning handling intentional, explicit, and aligned with engineering priorities.

Documenting warning policy in your contributor guide is equally important. New contributors often introduce deprecation warnings unintentionally, then CI failures look arbitrary. A short policy note explaining which warning categories are errors and why helps keep code reviews focused and prevents repeated confusion during onboarding.

Used carefully, this policy turns warnings into a measurable quality gate rather than background noise.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions