Last updated: Apr 9, 2024
Reading timeยท2 min
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.
my_list = [] # โ Ignore any exception try: print(my_list[100]) except: # ๐๏ธ this runs pass
We used a pass
statement to ignore an exception.
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.
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.
An alternative approach is to scope the except
block to a specific error.
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.
# โ๏ธ ZeroDivisionError: division by zero try: print(25 / 0) except IndexError: pass
You can also specify multiple exception classes in an except
block.
my_list = [] try: print(25 / 0) except (IndexError, ZeroDivisionError): # ๐๏ธ this runs pass
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.