Python: How to ignore an exception and proceed?
To ignore exceptions in Python, the standard approach is to use the try-except
block. Enclose the potential error-producing code within try
, and follow it with except
, paired with a pass
keyword to silent in-case warnings.
Example:
This method conceals any Exception
raised by risky_code()
, enabling your script to run firmly. Use this for non-critical exceptions only.
Using 'suppress' in contextlib to manage exceptions elegantly
Python 3.4 onwards, the contextlib
module presents a cleaner alternative to handle exceptions deliberately ignored. Particularly useful when dealing with specific sets of exceptions.
Here, the code tries to delete a file, and typically, if that file doesn't exist, it leads to raising a FileNotFoundError
. The suppress method ignores the exception and proceeds, avoiding unnecessary try-except
blocks.
Avoiding some common traps
Ignoring exceptions needs to be done with caution. It's important to specifically mention the type of exception you expect, as a bare except:
could lead to suppressing all exceptions, including those like KeyboardInterrupt
and SystemExit
that are fundamental to interrupt your program.
Wrong Way:
Right Way:
Moreover, **avoiding too broad **an exception, such as Exception
, can mask unexpected issues. So, your except
block needs to precisely cater to specific exceptions that you know could arise and are harmless to be ignored.
Delving deeper: Exception handling strategies
Handling exceptions requires in-depth understanding of underlying semantics. By using with suppress(..)
it becomes easier to focus on specific, non-critical exceptions for a one-off occurrence.
In case of patterns with suppressions required across various places, one can use a Decorator to wrap functions with an ignore_exception
functionality that will silently handle specific exception type(s).
Example:
In Python 2, you might encounter references to sys.exc_clear()
, a function to delete the last exception. While this may seem handy, it is outdated and deprecated in Python 3, encouraging more explicit exception handling.
Code Smarter with Exception Handling
Choosing the right strategy to handle exceptions depends greatly on your project requirements:
Elegance in code
Use with suppress(..)
to keep your code clean and optimized:
Debugging Made Easy
Record suppressed exceptions for better debugging and tracing:
Robust System Design
In larger systems, a custom exception handler can streamline exception handling:
This approach helps to manage and structure handling of different exceptions across a larger codebase.
Was this article helpful?