
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Ignore an Exception and Proceed in Python
An exception is an unexpected error or event that occurs during the execution of program. The difference between an error and an exception in a program is that, when an exception is encountered, the program deflects from its original course of execution whereas when an error occurs, the program is terminated. Hence, unlike errors, an exception can be handled. Therefore, you won't have a program crash.
However, in some cases of Python, the exception might not cause the program to terminate and will not affect the direction of execution hugely. Therefore, it is best to ignore such kind of exceptions. There are several ways to do this.
- Using the try/except block
- Using the suppress() method
Using the try/except Block
Try/except blocks will allow you to execute code and skip any errors that occur using the "pass" statement. This will essentially do nothing, but it will ignore any errors that occur. The syntax for this can be seen below -
try: code to be executed that may cause an exception except: pass
Ignoring a Specific Exception
You can ignore a specific exception using the except statement followed by the exception name, like AttributeError. Following is the basic syntax to do so -
try: # lines of code except AttributeError: pass
Example
In the following example, if an AttributeError occurs, it is ignored using pass statement-
try: "hello".some_undefined_method() except AttributeError: pass print("Program continues despite AttributeError.")
The output obtained is -
Program continues despite AttributeError.
Ignoring All Exceptions
If you want to ignore all exceptions regardless of their type, you can catch the base Exception class. Following is the basic syntax to do so -
try: # lines of code except Exception: pass
Example
In this example, we attempt to divide by zero. Since we are catching all exceptions, the program will skip the error and continue -
try: a = 10 / 0 except Exception: pass print("ZeroDivisionError was ignored and program continued.")
We get the following output -
ZeroDivisionError was ignored and program continued.
Example: Ignoring ZeroDivisionError in a Loop
In the following example, let us perform the division operation on an integer iteratively. Using for loop, we divide the integer object in a range 0-4; but zero division is not possible and the program will raise a ZeroDivisionError. This exception is ignored using the pass statement and execute the next iterations -
a = 16 for i in range(5): try: print(a/i) except: pass
The output for the program above is given below. The program ignores the first iteration as the first division is zero division -
16.0 8.0 5.333333333333333 4.0
Handling Specific Exceptions
Rather than ignoring all exceptions blindly, it is good to ignore only known exceptions that are safe to bypass. In the following example, we handle only the ValueError while continuing with the rest of the loop.
Example: Skipping Invalid Type Conversion
In this example, we try converting list items to integers. Strings that can't be converted are skipped using try-except and pass -
values = ['12', 'abc', '34', 'hello', '56'] numbers = [] for v in values: try: numbers.append(int(v)) except ValueError: pass print("Converted numbers:", numbers)
Following is the output obtained -
Converted numbers: [12, 34, 56]
Using suppress() Method
Another optimal way to ignore the exceptions, instead of using the try/except blocks, is the suppress() method. This method belongs to the contextlib module in Python.
However, unlike the try/except block, if an exception is raised inside this context, the entire lines of code within it will be suppressed by the python interpreter. Let us look at some examples to understand this in a better way.
Example: Suppressing ZeroDivisionError
In this example, we are trying to suppress/ignore the zero division error using the suppress() method -
import contextlib a = 16 with contextlib.suppress(ZeroDivisionError): div = a/0 print("Zero division error is suppressed")
The output for the program above will be produced as follows -
Zero division error is suppressed
Example: Entire Block Suppressed on One Exception
Even if single line of code within the suppress() method context raises an exception, the other lines enclosed in this block will also not be executed. This is the only drawback of this method. Let us see an example demonstrating the same below -
import contextlib a = 16 with contextlib.suppress(Exception): for i in range(5): print(a/i) print("The entire loop is not displayed")
On executing the program above, the output only displays the statement outside the context even though only one iteration of the loop raises an exception -
The entire loop is not displayed
Conclusion
In Python, you can ignore an exception and continue processing by using the "try...except" construct. If an exception occurs, the "except" block will be executed, and you can handle the exception accordingly. If you don't want to handle the exception, you can simply ignore it by using the "pass" keyword.