Errors are a natural part of programming. No matter how careful you are, mistakes will happen — maybe a wrong variable name, dividing a number by zero, or trying to open a file that doesn’t exist.

In Python, when something goes wrong, your program stops running and shows an error message (called an exception).
If you don’t handle these exceptions, your program will crash. But don’t worry — Python gives us tools to gracefully handle errors so your program can continue running.
Types of Errors in Python
Before diving into handling, let’s first see the types of errors:
- Syntax Errors – When you write code that Python cannot understand.
Example: print(“Hello” # Missing closing parenthesis Output: SyntaxError: unexpected EOF while parsing - Runtime Errors (Exceptions) – Errors that happen while the program is running.
Example: print(10 / 0) Output: ZeroDivisionError: division by zero - Logical Errors – The program runs but gives the wrong result because of incorrect logic.
Example: # Intended to calculate average, but forgot parentheses avg = 10 + 20 / 2 print(avg) # Wrong result
Exception Handling with try and except
The most basic way to handle errors in Python is by using try and except.
Example:
try:
num = int(input("Enter a number: "))
print(10 / num)
except:
print("Oops! Something went wrong.")
Here’s what happens:
- Code inside
try
is executed. - If any error occurs, Python jumps to
except
block instead of crashing.
Handling Specific Exceptions
Catching all errors blindly is not a good practice. Instead, you should handle specific exceptions.
try:
num = int(input("Enter a number: "))
print(10 / num)
except ValueError:
print("❌ Please enter a valid number.")
except ZeroDivisionError:
print("❌ Division by zero is not allowed.")
This way, you know exactly what went wrong.
Using else with try-except
Python also allows an else
block, which runs only if no error occurs.
try:
num = int(input("Enter a number: "))
print("Square:", num ** 2)
except ValueError:
print("Invalid input, please enter a number.")
else:
print("✅ Program ran successfully!")
The finally Block
Sometimes you need code that must run no matter what — for example, closing a file or releasing resources. That’s where finally
comes in.
try:
file = open("data.txt", "r")
print(file.read())
except FileNotFoundError:
print("File not found.")
finally:
print("Closing file (if opened).")
Raising Exceptions with raise
Sometimes, you may want to create your own error when a condition is not met.
age = int(input("Enter your age: "))
if age < 18:
raise ValueError("You must be at least 18 years old.")
else:
print("Access granted.")
Here, we forcefully raise a ValueError
if the user is under 18.
Custom Exceptions
You can even define your own exception classes to make programs more readable.
class NegativeNumberError(Exception):
pass
def check_number(num):
if num < 0:
raise NegativeNumberError("Negative numbers are not allowed.")
else:
print("Number is valid!")
try:
check_number(-5)
except NegativeNumberError as e:
print("❌ Error:", e)
Also Read: File Handling in Python
Best Practices for Error Handling
- ✅ Always catch specific exceptions (e.g.,
ValueError
,FileNotFoundError
). - ✅ Use
finally
to clean up resources (close files, release connections). - ✅ Avoid empty
except:
blocks — they make debugging hard. - ✅ Raise meaningful errors when input is invalid.
- ✅ Don’t overuse exceptions for normal logic.
Mini Project: Basic Calculator with Error Handling
Let’s build a calculator that handles errors gracefully.
def calculator():
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
operator = input("Choose operator (+, -, *, /): ")
if operator == "+":
print("Result:", num1 + num2)
elif operator == "-":
print("Result:", num1 - num2)
elif operator == "*":
print("Result:", num1 * num2)
elif operator == "/":
print("Result:", num1 / num2)
else:
print("❌ Invalid operator")
except ValueError:
print("❌ Please enter numbers only.")
except ZeroDivisionError:
print("❌ Division by zero not allowed.")
finally:
print("Thank you for using calculator!")
calculator()
Sample Run:
Enter first number: 10
Enter second number: 0
Choose operator (+, -, *, /): /
❌ Division by zero not allowed.
Thank you for using calculator!
Final Thoughts
Error handling makes your Python programs more reliable and professional. Instead of crashing, your code will gracefully handle problems and guide the user with helpful messages.
From basic try-except
to custom exceptions, mastering error handling is a must if you want to build real-world applications.
FAQs – Error Handling in Python
What is the difference between syntax errors and exceptions?
Syntax Errors happen when your code is written incorrectly (e.g., missing colon, wrong indentation). Python won’t run until you fix it.
Exceptions occur while the program is running (e.g., dividing by zero, file not found). These can be handled with error handling.
How do you raise custom errors in Python?
You can use the raise
keyword to create custom exceptions. Example:
What is the benefit of finally in Python error handling?
finally
ensures that important code (like closing a file or releasing resources) always runs, even if an error occurs.
Why is error handling important in Python projects?
It makes your programs more reliable, user-friendly, and professional by preventing sudden crashes and giving meaningful error messages.
What’s Next?
In the next post, we’ll learn about the Date and Time in Python