Python Exception Handling: How to Fix Ignored Messages

When Python prints “Exception ignored in,” check the traceback to find the code that raised the exception. Python uses this message when an exception cannot be returned to an ordinary caller, often during cleanup.

I’ll explain what the message means and show how to repair the code the traceback points to.

TL;DR: Fix the code that raises the ignored exception

“Exception ignored in” reports an unraisable exception, often raised by cleanup code after Python has no normal caller to receive it. Find the object or finalizer named in the traceback and repair that code instead of wrapping unrelated work in another try/except.

  • Read the traceback after the message and identify the function or object being finalized.
  • Handle expected failures inside cleanup, or remove fragile work from __del__.
  • Use sys.unraisablehook for temporary diagnostics, not to hide the underlying defect.

What does “Exception ignored in” mean in Python?

Python uses this message when an exception occurs in a place where it cannot return that exception to an ordinary caller.

sys.excepthook handles uncaught top-level errors, whereas sys.unraisablehook receives unraisable-exception details for diagnostics.

A generator frame can point to a yield during close, while a package method can point to its documented cleanup API or version history.

A regular exception moves from its failing operation through active calls until a handler matches its class or a parent class. Python checks except clauses in order, so place a specific class before its parent.

Common exception names describe different failure conditions:

ExceptionWhat it signals
ValueErrorA value has the right type but is unsuitable for the operation
TypeErrorAn operation received a value of an unsupported type
OSErrorAn operating-system operation such as file access failed

When a handler raises a new exception, Python records the earlier one in __context__. Use raise NewError(…) from exc to show it as the explicit cause.

A SyntaxError is raised while Python parses source. If your program compiles a string at runtime, put any recovery handler around compile(). Catch runtime failures from exec() around that call instead.

A try statement’s else suite runs when its body finishes without an exception, and errors from else skip that try statement’s except clauses. Its finally suite runs on either path, so place success-only work in else and cleanup in a context manager or finally.

Subclass Exception when a domain failure needs a stable name or structured attributes, such as a ConfigurationError that stores the missing setting. Use a shared domain base only when callers need one handler for related failures.

The exact deallocator wording and object address shown here come from this Python 3.14.7 run.

class BrokenCloser:
    def __repr__(self):
        return "BrokenCloser"

    def __del__(self):
        raise RuntimeError("close failed")


resource = BrokenCloser()
del resource
print("Program continues")

I ran python3 ignored_exception_demo.py. The terminal showed:

rishabh@askpython:~$ python3 ignored_exception_demo.py
Exception ignored while calling deallocator <function BrokenCloser.__del__ at 0xf4ed13781590>:
Traceback (most recent call last):
  File "/home/ubuntu/.cache/journaldev-article-runs/askpython-exception-ignored-in-messages-20261028T183606Z-054e6ec16555/ignored_exception_demo.py", line 6, in __del__
    raise RuntimeError("close failed")
RuntimeError: close failed
Program continues
Python destructor exception traceback from the BrokenCloser example

The RuntimeError identifies the failure type, and “Program continues” shows execution reaches the next statement. The traceback identifies the failing method and source line.

How to trace and fix an ignored exception

I ran the example as a standalone script because it keeps the destructor report separate from other application cleanup.

Step 1: Locate the failing cleanup method

Read every frame in the traceback and inspect the named cleanup operation, then trace ownership and the point where cleanup begins.

Step 2: Move cleanup into an explicit lifetime

Use a context manager or explicit close for files so the application handles cleanup while it owns the resource. For a variable resource count, ExitStack registers each context and closes them in reverse order if acquisition or later work fails.

For asynchronous resources, use async with or await the documented close method while the coroutine is active. A synchronous destructor cannot await cleanup after the event loop stops, so keep async teardown inside an async context manager. For async generators, contextlib.aclosing awaits aclose() when its async with block exits.

Step 3: Make a finalizer safe to run late

Python’s data model warns that __del__ can run during interpreter shutdown after module globals and services have changed. Keep a destructor short and independent of application services. If both close() and __del__ release a resource, make close() idempotent so fallback finalization cannot release it twice.

A finalizer may run in an arbitrary thread, so waiting on another thread can deadlock. An object still alive at interpreter exit may skip __del__, which is another reason to close resources before shutdown.

weakref.finalize registers a callback without adding work to __del__, and by default it may run at interpreter exit. Do not pass the referent or a bound method that retains it as callback state, because that can keep the object alive. Exceptions from the callback still reach standard error and cannot propagate, so it does not replace explicit close when a caller must respond.

Compare the failing method with these checks before changing code:

Traceback clueWhat to inspectSafer response
__del__ in your moduleOperations that can raise or rely on shutdown stateUse explicit close and keep finalization minimal
Generator ignored GeneratorExitA yield inside code that handles GeneratorExitRun cleanup, then let the generator stop
Third-party method or package pathPackage version, issue tracker, and object lifetimeUpdate or report a minimal reproduction to its maintainer
Failure only while the process exitsThreads, pending tasks, callbacks, and module globalsShut resources down before interpreter finalization

Common errors with ignored exceptions

This comparison includes missing paths because open() raises FileNotFoundError during an ordinary call.

CaseWhy the handler misses itNext check
Destructor raisesPython reports exceptions from __del__ through the unraisable hookMove work into an explicit close path
Context manager exit failsAn error inside __exit__ is separate from an exception in the with bodyInspect __exit__ and handle only expected cleanup failures
Missing file at open()This is an ordinary exception raised during the callCatch FileNotFoundError around the open operation if recovery is valid
Library reports error at shutdownThe library may finalize after your handler has returnedCheck its documented close method and current issue tracker

For general syntax, see Python exception handling with try, except, and finally. Its examples cover ordinary handlers rather than delayed finalization.

CPython issue 130522 describes a specific thread-cleanup failure at process exit. Its setup is narrow, so compare your traceback before using a workaround from that report.

For temporary diagnostics, replace sys.unraisablehook with a focused callback, then restore the default when the investigation ends. This changes what is recorded, not the cleanup failure itself.

The hook receives an UnraisableHookArgs object with fields that help identify the failure:

FieldValue
exc_typeException class
exc_valueException instance
exc_tracebackTraceback object
err_msgOptional message
objectObject associated with the failure

Keep only a text summary after recording the details. Holding the associated object or its exception value can prolong its lifetime or resurrect it during finalization.

For exception classes and their relationships, see Exceptions in Python: Types and Handling. Python’s tutorial describes finally and with cleanup. The data model reference covers destructor limits.

When a with body raises, __exit__ receives the active exception and can suppress it by returning true, while a new error from __exit__ reaches an outer handler.

A generator-based context manager yields once at entry and puts cleanup in finally so it also runs when the with body raises.

A finally clause runs on every try exit, but a new exception or return from it can replace the pending result, so reserve it for cleanup.

Closing a generator injects GeneratorExit at its suspended yield. A yield during cleanup raises RuntimeError instead of completing closure.

GeneratorExit inherits directly from BaseException, so an except Exception clause skips generator closure. Catching BaseException also intercepts process-level signals such as KeyboardInterrupt, so use a narrower type when possible.

For a third-party traceback, record the Python and package versions with a minimal reproduction. Check the package’s release notes and issue tracker for a matching cleanup bug before changing versions. The words “Exception ignored” alone do not show whether the defect belongs to your code, a dependency, or an interpreter edge case.

Python’s ExitStack documentation covers dynamically acquired resources. The yield expression reference documents generator syntax.

Conclusion: Fix the cleanup path

Use the traceback to identify the cleanup method, then test it on normal exit and on an error path. Record the dependency version when a package owns that method so the failure can be reproduced.

Use sys.unraisablehook documentation when you need to inspect the reporting hook, and keep the broader AskPython exception-handling guide nearby for ordinary handlers.

FAQ

These answers distinguish this diagnostic from common exception-handling questions.

Why does try/except not catch “Exception ignored in”?

The message reports an unraisable exception, such as one raised during object finalization. The original call stack may no longer exist, so an outer handler cannot receive it. Fix or handle the failure at its cleanup source.

Does a missing file cause “Exception ignored in”?

Opening a missing path normally raises FileNotFoundError during open(). It is an ordinary exception that a matching try/except can catch. The ignored-exception message points to a separate unraisable failure.

What does “generator ignored GeneratorExit” mean?

Python sent GeneratorExit while closing a generator, but the generator yielded another value instead of finishing. Do cleanup without yielding when the generator is being closed.

Can I hide the message with sys.unraisablehook?

You can customize the hook for diagnostics, but suppressing its output does not fix the exception. Keep the report while locating and correcting the cleanup failure.

Can an exception in finally replace the original error?

Yes. A new error raised while finally runs becomes the exception leaving that code. Python keeps the earlier one as context, which the traceback can show. Use cleanup code that preserves the original failure.

Is __del__ guaranteed to run when Python exits?

No. An object still alive at interpreter exit may skip __del__, and module globals may have changed. Close resources before shutdown so failures reach application code.

How do I preserve the original error when raising another one?

Use raise NewError(…) from exc inside the handler to set an explicit cause. The traceback then shows the lower-level failure that led to the new exception.

Rishabh Das
Rishabh Das
Articles: 47