Nothing kills a smooth-running Python script faster than a nasty exception crashing your program midrun. And yet, exceptions show up all the time errors in input, server issues, invalid operations. That’s why exception handling is a must-know skill. Ready to make your code rock-solid? Let’s dive in.

Imagine you’re building a calculator app. Someone enters / boom, ZeroDivisionError and your entire app crashes. Ouch.
Exception handling helps you:
try:
Copy Code
x = int(input("Enter a number: "))
y = int(input("Enter another: "))
print("Result:", x / y)
except ZeroDivisionError:
print(" Cannot divide by zero!")Output Example:
Enter a number: 10
Enter another: 0
Cannot divide by zero!
Simple and clean. Your code inside try runs; if an exception occurs, it jumps to the matching except block.
Copy Code
try:
x = int(input("Enter a number: "))
y = int(input("Enter another: "))
print("Result:", x / y)
except ValueError:
print("Please enter integers only.")
except ZeroDivisionError:
print("Cannot divide by zero.")Output Examples:
Enter a number: a
Please enter integers only.
Powerful way to handle diverse errors distinctly.
Copy Code
try:
f = open("data.txt")
data = f.read()
except FileNotFoundError:
print("Sorry, file not found.")
else:
print("File content:", data)
finally:
print("Closing file.")
try:
f.close()
except:
passSometimes you want to raise your own errors:
Copy Code
def get_age():
age = int(input("Age: "))
if age < 0:
raise ValueError("Age can’t be negative!")
return age
try:
print(get_age())
except ValueError as ve:
print("Error:", ve)Creates meaningful, contextspecific exceptions.
Copy Code
try:
risky_code()
except Exception as e:
print("Something went wrong:", e)Be specific when possible catching all exceptions can hide bugs. But it's useful for top-level logging or cleanup.
Copy Code
def get_num(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("That’s not a valid number try again.")
x = get_num("Enter num1: ")
y = get_num("Enter num2: ")
try:
choice = input("Choose (+, -, *, /): ")
if choice == "+":
result = x + y
elif choice == "-":
result = x - y
elif choice == "*":
result = x * y
elif choice == "/":
result = x / y
else:
raise ValueError("Invalid operation!")
print("Result:", result)
except ValueError as ve:
print("Error:", ve)
except ZeroDivisionError:
print("Cannot divide by zero.")Handles input errors, invalid choices, division by zero all smooth and user-friendly.
Want to master exception handling and other Python essentials? Check out Uncodemy’s Python Programming Course. They offer hands-on projects, real-world examples, and clear explanations to help you code smarter and cleaner.
1. What’s the difference between Exception and BaseException?
BaseException is the superclass of all exceptions, including system-level ones like SystemExit. Stick with Exception in most cases.
2. Can I use try…finally without except?
Yes. Just use it if you always want cleanup like releasing resources even without error handling.
3. Is it bad to catch multiple exceptions in one go?
It’s okay if you handle them similarly. Eg. except (ValueError, TypeError):.
4. Will finally run if I return inside try?
Yes. finally always executes even on return, break, or sys.exit().
5. Should I use exceptions for control flow?
Not really. Use exceptions for exceptional cases not as normal logic.
Exception handling isn’t just a coding safeguard it lets your script communicate gracefully, recover intelligently, and prevent awkward crashes.
Once you apply these patterns, your Python code will feel more professional, robust, and ready for real-world use.
Personalized learning paths with interactive materials and progress tracking for optimal learning experience.
Explore LMSCreate professional, ATS-optimized resumes tailored for tech roles with intelligent suggestions.
Build ResumeDetailed analysis of how your resume performs in Applicant Tracking Systems with actionable insights.
Check ResumeAI analyzes your code for efficiency, best practices, and bugs with instant feedback.
Try Code ReviewPractice coding in 20+ languages with our cloud-based compiler that works on any device.
Start Coding
TRENDING
BESTSELLER
BESTSELLER
TRENDING
HOT
BESTSELLER
HOT
BESTSELLER
BESTSELLER
HOT
POPULAR