Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Requests Readtimeout Error
Next article icon

How to Fix - Timeouterror() from exc TimeoutError in Python

Last Updated : 02 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

We can prevent our program from getting stalled indefinitely and gracefully handle it by setting timeouts for external operations or long-running computations. Timeouts help in managing the execution of tasks and ensuring that our program remains responsive. In this article, we will see how to catch Timeouterror() from exc TimeoutError in Python.

What is Timeouterror() from exc TimeoutError in Python?

In Python's asyncio tasks, a timeout error is raised when an operation takes longer than the allotted time to finish. This error is raised to show that the job was not completed in the allotted amount of time. It is often used in asynchronous programming to deal with tasks that take too long to finish. Developers can catch this problem and use the right way to deal with it or try again to manage timeouts well in their asyncio programs.

Error Syntax

TimeoutError() from exc TimeoutError

below, are the reasons for the occurrence of Python TimeoutError() from exc TimeoutError in Python:

  • Slow Operations
  • Infinite Loops

Slow Operations

In below code the fetch_data function pretends to wait for a slow internet connection by pausing for 2 seconds. In main, a timeout of 1 second is set using asyncio.TimeoutError. When asyncio.wait_for waits for fetch_data to finish, it takes too long, so it gives a TimeoutError.

Python3
import asyncio  async def my_task():     await asyncio.sleep(3)  # Simulate some long-running operation     return "Task completed"  async def main():     result = await asyncio.wait_for(my_task(), timeout=2)     print(result)  asyncio.run(main()) 


Output:

 File "<main.py>", line 8, in main
File "/usr/local/lib/python3.11/asyncio/tasks.py", line 502, in wait_for
raise exceptions.TimeoutError() from exc TimeoutError

Infinite Loops

In below code the Infinite_loop is a function that keeps running forever. In main, a timeout of 2 seconds is set, but because the loop never ends, it takes too long, resulting in a TimeoutError.

Python3
import asyncio  async def my_task():     while True:         await asyncio.sleep(1)  # Infinite loop, simulating ongoing task  async def main():     await asyncio.wait_for(my_task(), timeout=2)  asyncio.run(main()) 

Output:

File "<main.py>", line 8, in main
File "/usr/local/lib/python3.11/asyncio/tasks.py", line 502, in wait_for
raise exceptions.TimeoutError() from exc TimeoutError

Solution for Timeouterror() from exc TimeoutError in Python

Below, are the approaches to solve Python "Timeouterror() from exc TimeoutError" in Python:

  • Using asyncio.timeout()
  • Using asyncio.wait_for()

Using asyncio.timeout()

Below, code defines an asynchronous task that pauses for 5 seconds and a main coroutine that waits for it to complete within 2 seconds, printing success if completed or a timeout message if not. Then, it executes the main coroutine using asyncio.run().

Python3
import asyncio  async def long_running_task():     await asyncio.sleep(5)  async def main():     try:         await asyncio.wait_for(long_running_task(), timeout=2)         print("Task completed successfully.")     except asyncio.TimeoutError:         print("The task took too long and timed out.")  asyncio.run(main()) 

Output
The task took too long and timed out. 

Using asyncio.wait_for()

Below, code defines an asynchronous task that pauses for 5 seconds and a main coroutine that waits for it to complete within 2 seconds. It prints the result if completed or a timeout message if not. Finally, it executes the main coroutine using asyncio.run().

Python3
import asyncio  async def long_running_task():     await asyncio.sleep(5)    async def main():     try:         result = await asyncio.wait_for(long_running_task(), timeout=2)         print("Task completed:", result)     except asyncio.TimeoutError:         print("Task timed out!")  asyncio.run(main()) 

Output
Task timed out! 

Next Article
Python Requests Readtimeout Error

K

kumarwatsal43
Improve
Article Tags :
  • Python
  • Python Programs
  • Python How-to-fix
  • Python Errors
Practice Tags :
  • python

Similar Reads

  • How to Fix ImportError: Cannot Import name X in Python
    We are given an error "Importerror: Cannot Import Name ‘X’ From ‘Collections’ " in Python and our task is to find the solution for this error. In this article we will see the reasons for occurring and also the solution for the Importerror: Cannot Import Name ‘X’ From ‘Collections’ " error in Python.
    3 min read
  • How to fix "SyntaxError: invalid character" in Python
    This error happens when the Python interpreter encounters characters that are not valid in Python syntax. Common examples include: Non-ASCII characters, such as invisible Unicode characters or non-breaking spaces.Special characters like curly quotes (“, ”) or other unexpected symbols.How to Resolve:
    2 min read
  • How To Return 0 With Divide By Zero In Python
    Dividing a number by zero is a big problem in math, and it can cause errors that suddenly stop your Python program. However, what if you could smoothly deal with this issue and make your program return a specific value, such as 0, instead of crashing? This article looks into different methods to acc
    3 min read
  • How To Fix - Python RuntimeWarning: overflow encountered in scalar
    One such error that developers may encounter is the "Python RuntimeWarning: Overflow Encountered In Scalars". In Python, numeric operations can sometimes trigger a "RuntimeWarning: overflow encountered in a scalar." In this article, we will see what is Python "Python Runtimewarning: Overflow Encount
    3 min read
  • Python Requests Readtimeout Error
    Python's requests library is a powerful tool for making HTTP requests, but like any software, it is not without its quirks. One common issue users encounter is the ReadTimeout error, which occurs when the server takes too long to send a response. In this article, we'll delve into the ReadTimeout err
    3 min read
  • Runtimeerror: Maximum Recursion Limit Reached in Python
    In this article, we will elucidate the Runtimeerror: Maximum Recursion Limit Reached In Python through examples, and we will also explore potential approaches to resolve this issue. What is Runtimeerror: Maximum Recursion Limit Reached?When you run a Python program you may see Runtimeerror: Maximum
    5 min read
  • Measure time taken by program to execute in Python
    Measuring the execution time of a Python program is useful for performance analysis, benchmarking, and optimization. Python provides several built-in modules to achieve this with ease. In this article, we'll explore different ways to measure how long a Python program takes to run. Using the time Mod
    3 min read
  • How to Run Two Async Functions Forever - Python
    In Python, asynchronous programming allows us to run multiple tasks concurrently without blocking the main program. The most common way to handle async tasks in Python is through the asyncio library. Key Concepts Coroutines: Functions that we define using the async keyword. These functions allow us
    4 min read
  • try-except vs If in Python
    Python is a widely used general-purpose, high level programming language. It was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code. Python is a programming language that lets you work quickly and integrate systems more eff
    3 min read
  • How to Fix - UnboundLocalError: Local variable Referenced Before Assignment in Python
    Developers often encounter the UnboundLocalError Local Variable Referenced Before Assignment error in Python. In this article, we will see what is local variable referenced before assignment error in Python and how to fix it by using different approaches. What is UnboundLocalError: Local variable Re
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences