What You Will Learn
In this lesson, you will learn:
- Why error handling is important
- What
tryandexceptdo - How to handle common chatbot errors
- How to show user-friendly error messages
By the end of this lesson, your chatbot will not crash when an error occurs.
Quick Answer
Error Handling means managing unexpected problems without crashing the program. Instead of showing a long error message, your chatbot can explain what went wrong and continue running.
Why Do We Need Error Handling?
Imagine your chatbot is working perfectly. Then one day:
- Your internet connection is lost.
- The API key is incorrect.
- The API request fails.
Without error handling, your chatbot stops immediately and shows a long Python error. Example:
Traceback (most recent call last):
...
Exception...
A beginner usually doesn’t know what this message means. Instead, we should show a simple message like this:
Something went wrong.
Please check your internet connection or API key.
This makes your chatbot much easier to use.
What is try and except?
Python provides two keywords for handling errors.
try:
# Code that may cause an error
except:
# Code that runs if an error occurs
Think of it like this:
- try → “Try to run this code.”
- except → “If something goes wrong, run this code instead.”
Step 1: Find This Code
Open app.py.
Find this part of your chatbot.
response = client.responses.create(
model="gpt-5",
instructions="""
You are a friendly Python teacher.
Explain every topic in simple English.
Keep your answers short.
Always include an example whenever possible.
""",
input=user_message,
previous_response_id=previous_response_id
)
print("\nAI:", response.output_text)
previous_response_id = response.id
We’ll protect this code with try and except.
Step 2: Add try
Place try: above the API request.
try:
Now indent the API request and the related code inside the try block.
Step 3: Add except
After the try block, add:
except Exception as error:
print("\nSomething went wrong.")
print(error)
If an error happens, the chatbot will display a message instead of crashing.
Complete Code
Only the highlighted part of your chatbot changes.
while True:
user_message = input("You: ")
if user_message.lower() == "exit":
print("Goodbye!")
break
try:
response = client.responses.create(
model="gpt-5",
instructions="""
You are a friendly Python teacher.
Explain every topic in simple English.
Keep your answers short.
Always include an example whenever possible.
""",
input=user_message,
previous_response_id=previous_response_id
)
print("\nAI:", response.output_text)
previous_response_id = response.id
except Exception as error:
print("\nSomething went wrong.")
print(error)
How Does It Work?
Let’s understand the flow.
Case 1: Everything Works
You: What is Python?
AI: Python is a beginner-friendly programming language.
The chatbot works normally.
Case 2: Internet Is Disconnected
Instead of crashing, your chatbot shows:
Something went wrong.
Please check your internet connection.
The program keeps running.
Case 3: Invalid API Key
Instead of a confusing Python error, you’ll know where to start looking.
Something went wrong.
Please check your API key.
Why Is This Better?
Without error handling:
- Program crashes
- Confusing error messages
- Bad user experience
With error handling:
- Program stays running
- Easier to understand
- Better experience for users
Common Mistakes
Forgot Indentation
Everything inside the try block must be indented.
Incorrect indentation will cause an error.
except Before try
Always write:
try:
...
except:
...
Never write except before try.
Removing the Error Variable
This is correct.
except Exception as error:
The error variable contains information about what went wrong.
Key Points
- Use
tryto run code that may fail. - Use
exceptto handle errors. - Error handling prevents your chatbot from crashing.
- Friendly messages make your chatbot easier to use.
Mini Quiz
1. What does try do?
A. Stops the program
B. Runs code that might cause an error
C. Deletes errors
D. Restarts Python
Answer: B
2. What does except do?
A. Ignores Python
B. Handles an error
C. Installs packages
D. Creates variables
Answer: B
3. Which keyword catches an error?
A. catch
B. except
C. error
D. fail
Answer: B
4. Should every API request use error handling?
A. Yes
B. No
Answer: A
5. What is the main benefit of error handling?
A. Smaller code
B. Faster internet
C. Prevents the program from crashing
D. Creates API keys
Answer: C
Practice Exercise
Test your chatbot.
Try these situations.
- Disconnect your internet and run the chatbot.
- Enter an incorrect API key in the
.envfile. - Restore the correct API key and run the chatbot again.
Notice how your chatbot behaves in each case.
Lesson Summary
Great job! Your chatbot is now more reliable. Instead of crashing when something goes wrong, it shows a helpful message and allows you to understand the problem more easily. Error handling is a small change, but it is an important step toward building professional AI applications.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
Shubhranshu Shekhar is a coding instructor, mentor, and founder of VSIT Delhi with 20+ years of teaching experience (since 2004). He has guided many students who are now working in multinational companies and specializes in Full Stack Development, Python, Digital Marketing, and Data Analytics.
