Using try without except (ignoring exceptions) in Python

avatar

Borislav Hadzhiev

Last updated: Aug 17, 2022

banner

Photo from Unsplash

Using try without except (ignoring exceptions) in Python #

Use the pass statement to use a try block without except. The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.

main.py
my_list = [] # ✅ Ignore any exception try: print(my_list[100]) except: # 👇️ this runs pass # ✅ Ignore only IndexError exceptions try: print(my_list[100]) except IndexError: # 👇️ this runs pass

We used a pass statement to ignore an exception.

The except statement in the first example handles an exception of any type.

The code in the try block could raise any exception and it would get passed to the except block.

main.py
my_list = [] # ✅ Ignore any exception try: # 👇️ raises ValueError my_list.remove(1000) except: # 👇️ this runs pass

The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.

In general, using an except statement without explicitly specifying the exception type is considered a bad practice.

This is mostly because catching any error makes your code less intuitive and more difficult to read.

An alternative approach is to scope the except block to a specific error.

main.py
my_list = [] try: print(my_list[100]) except IndexError: # 👇️ this runs pass

The except block only handles IndexError exceptions.

If an exception of any other type is raised, the except block won't handle it.

For example, the following code raises a ZeroDivisionError in the try block and crashes the program.

main.py
# ⛔️ ZeroDivisionError: division by zero try: print(25 / 0) except IndexError: pass

You can also specify multiple exception classes in an except block.

main.py
my_list = [] try: print(25 / 0) except (IndexError, ZeroDivisionError): # 👇️ this runs pass
The except block runs because it handles the ZeroDivisionError that gets raised in the try block.

If you have to specify multiple exception classes, make sure to wrap them in parentheses.

You can view all of the exception classes in Python in the Exception hierarchy list in the docs.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.