Handle the queue.Empty exception in Python

avatar

Borislav Hadzhiev

Thu Jun 16 20221 min read

Handle the queue.Empty exception in Python #

Use a try/except statement to handle the queue. Empty exception in Python. You can use the get() method in the try block and catch the queue.Empty exception in the except block.

main.py
import queue q = queue.Queue() q.get(False) try: item = q.get(False) # 👉️ do work here # 👇️ indicate task complete q.task_done() except queue.Empty: print('queue.Empty exception') # 👉️ handle empty queue exception pass

The Queue.get method removes and returns an item from the queue.

We passed False to the method to make it non-blocking.

If the an item is not immediately available in the queue, the method raises a queue.Empty exception.

You can do all the necessary work in the try block and call the Queue.task_done method at the end to indicate that the task is complete.

We can use the task_done() method to tell the queue that the task is complete after each call to the get() method to fetch a task.

You can also simplify this a bit by using an else block.

main.py
import queue q = queue.Queue() try: item = q.get(False) # 👉️ do work here except queue.Empty: print('queue.Empty exception') # handle empty queue exception pass else: # 👇️ indicate task complete q.task_done()

The try/except statement has an optional else clause.

The else block runs only if the try block doesn't raise an exception.

Use the search field on my Home Page to filter through my more than 1,000 articles.