In today’s article, we will look at how we properly ignore exceptions in Python.
As with everything in life, there is a correct way to do things and there are other ways! We will start by seeing the incorrect way of ignoring exceptions and see what is incorrect about them and then proceed to learn about the correct way to ignore exceptions. Without further ado, let’s begin!
Ignoring Exceptions Incorrectly
Here’s a simple piece of code:
try:
#code that raises an exception
except:
pass
Here we catch whatever exception is raised in the try block using the “except: ” statement. Not mentioning what specific exception to catch using the syntax “exception ExceptionName” will catch anything and everything! I suggest reading this article to learn more about what the line “except: ” actually does in the background.
Catch all errors except KeyboardInterrupt
At first, it might seem pretty harmless, but we are trying to execute something in the try block. And if some error occurs there we simply ignore whatever exception was raised and continue as if nothing happened.
While it looks like it solves the error problem immediately, there are several problems with this approach!
Firstly, ignoring an exception without a good reason means your code has silently failed. When something has gone south, you want to be alerted about it to fix it. This is not possible in this scenario and even leads to hard-to-debug situations in the future.
Secondly, we lose precious information about the exception in this case. Exception objects in Python can contain a variety of information about what went wrong which can be used to debug, report, log, etc. To know more about what you can do with exception objects, click here.
Along with this, a ton of additional issues such as security risks, resource leaks, low-quality code, and poor user experience come along when you ignore an exception incorrectly!
Here are some situations where you would never want to ignore exceptions:
- Ignoring a critical error: Always deal with critical exceptions and never ignore them. This could lead to a multitude of problems. These could snowball and would become a headache to deal with in the future.
- Security or data leakage: Exceptions that deal with security or with the safekeeping of sensitive data such as authentication or permission-related matters need to be taken seriously.
That being said, there are situations where you might want to ignore an exception, let’s look at that now.
The Correct Way of Ignoring Exceptions
When to Ignore Exceptions?
Here by ignoring we mean logging and moving on!
Whilst ignoring exceptions may not sound smart at first, it may be a valid strategy in certain situations:
#1 Logging and monitoring real-time applications:
Sometimes you want your program to simply log the error and move on with the execution as your application needs to be real-time.
This is common in server applications where you don’t want the entire service to come to a stop because of one error. For example, when streaming a video missing a few frames now and then is okay to ignore it, logging and moving on is the recommended approach to debug performance issues.
#2 Optional “non-critical” features:
In case your program relies on features that are not considered critical, you can simply ignore the error that pops up during these times. This way your “critical features” can continue to work.
For example, if your code for the non-critical feature tries to import an optional external library, and in the scenarios where it is missing, you can simply ignore and log the ModuleNotFoundError that will be raised and proceed.
#3 Fallback mechanisms:
Sometimes you may have a fallback mechanism set up that lets your program continue running, even if certain non-critical exceptions occur. For example, your system may have 2 network connections and if one stops working you can always use the 2nd one.
In these cases, the exceptions are considered non-critical and can simply be ignored or logged to be dealt with later.
Now that we know when to ignore exceptions, let’s next see how to do that!
Ignoring a specific type of exception
In some cases you may want to ignore a specific type of exception, in this case, you can use the syntax mentioned below
try:
#code that raises an exception
except SpecificException:
# log your error and move on
Here’s an example where you’re trying to only find out if a file exists or not and are ignoring other problems:
try:
with open('myfile.txt', 'r') as file:
content = file.read()
print(content)
print("The file was found.")
except PermissionError:
print(f"Please run the app with admin rights")
except FileNotFoundError:
print(f"The file was not found.")
Ignoring all exceptions
Ignoring all exceptions is not recommended except in rare cases. By rare I mean really rare!
For instance, imagine you are writing a program to clean up temporary files and you want it to ignore any errors during the process to avoid interruptions.
The syntax for that would simply be:
try:
#code that is cleaning up temporary files
except Exception:
pass
Here we catch the class Exception to handle pretty much all the exceptions in Python. If you’re looking to learn more about exception classes and subclasses, read here.
In such cases, logging is optional, depending on your use case!
Now that we have covered the topic of ignoring exceptions, next you might wanna learn how to debug exceptions the professional way
Else try one of the following articles instead!
Related Articles
Python: “try-except-else-finally” Usage Explained!
7 Most Common In-Built Exceptions in Python!
Exceptions in Python: Explained for Beginners!
Thanks to Namazi Jamal for his contributions in writing this article!