Using try without except (ignoring exceptions) in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
2 min

banner

# 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

using try without except

The code for this article is available on GitHub

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 code for this article is available on GitHub

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.

# Ignoring only specific errors

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

ignoring only specific errors

The code for this article is available on GitHub

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

# Ignoring multiple, specific errors

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

ignoring multiple specific errors

The code for this article is available on GitHub
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.

Copyright ยฉ 2024 Borislav Hadzhiev