Python Basics — Day 14 Exception Handling (try / except)
Aspiring Full-Stack Developer | Python · Django · React · SQL | documenting my learning journey
Building skills in Python and full-stack development, with a focus on web apps and system design
Junior developer in training — Python, Django, React — preparing for a career in full-stack engineering
From Python basics to full-stack projects, sharing my progress as I grow into a developer
Future full-stack engineer | Learning in public: Python, APIs, Databases, and Web Development
01. What is an Error (Exception)?
An error occurs when something goes wrong during execution → program stops.
Examples: dividing by zero, invalid index access, missing file.
print(10 / 0) # ZeroDivisionError
numbers = [1, 2, 3]
print(numbers[5]) # IndexError
02. Basic try / except Structure
try:
# Code to execute
except:
# Code to run if an error occurs
Example:
try:
x = int(input("Enter a number: "))
print("You entered:", x)
except:
print("That is not a number!")
03. Handling Specific Exceptions
You can handle different types of exceptions separately.
try:
num = int("abc") # Raises ValueError
except ValueError:
print("Cannot convert to integer.")
04. Handling Multiple Exceptions
try:
a = [1, 2, 3]
print(a[5]) # IndexError
print(10 / 0) # ZeroDivisionError
except IndexError:
print("List index out of range!")
except ZeroDivisionError:
print("Cannot divide by zero.")
05. Using else and finally
else→ runs only if no exception occursfinally→ always runs, whether an exception occurs or not
try:
n = int(input("Enter a number: "))
except ValueError:
print("Invalid input.")
else:
print("Valid number:", n)
finally:
print("Program finished.")
06. Using Exception Objects
try:
x = 10 / 0
except Exception as e:
print("Error occurred:", e)
07. Practice Examples
Example 1: Prevent Division by Zero
try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
print(a / b)
except ZeroDivisionError:
print("Cannot divide by zero.")
Example 2: File Reading
try:
with open("not_exist.txt", "r", encoding="utf-8") as f:
data = f.read()
except FileNotFoundError:
print("File not found!")