Python

Python Basics

Data Structures in Python

Control Flow and Loops

Functions and Scope

Object-Oriented Programming (OOP)

Python Programs

Handling Exceptions (try, except) in Python

Programming is never perfect on the first try—errors happen. Python gives us a powerful way to manage these unexpected issues through exception handling using try, except, else, and finally. Instead of letting your program crash, you can catch errors, show useful messages, or run backup code.

This makes your program safer, more professional, and easier to debug.


🧠 What Is Exception Handling in Python?

Exception handling is a technique used to manage runtime errors—these errors occur while your program is executing. Without exception handling, a single mistake (like dividing by zero or reading a missing file) can crash your whole program.

Python solves this with:

  • try → Code that may cause an error
  • except → What to do if an error happens
  • else → Runs only when no error occurs
  • finally → Runs no matter what (cleanup code)

---------------------------------

🟦 1. TRY and EXCEPT BASICS

---------------------------------

The simplest form:

try:
# risky code
except:
# backup code

This prevents the program from stopping when something goes wrong.


⭐ Example 1: Handling Division Errors

try:
num = int(input("Enter a number: "))
print(100 / num)
except:
print("You cannot divide by zero or enter invalid input!")

⭐ Example 2: Handling Invalid Integer Input

try:
age = int(input("Enter your age: "))
print("In 5 years, you will be:", age + 5)
except:
print("Please enter a valid number for age.")

⭐ Example 3: Accessing a List Index That May Not Exist

try:
data = [10, 20, 30]
pos = int(input("Enter index: "))
print(data[pos])
except:
print("Index does not exist! Try a number between 0 and 2.")

------------------------------------------

🟩 2. Multiple except Blocks

------------------------------------------

You can catch different errors separately.


⭐ Example 1: Different Error Types

try:
x = int(input("Number: "))
print(10 / x)
except ZeroDivisionError:
print("You tried dividing by zero!")
except ValueError:
print("Only numbers are allowed!")

⭐ Example 2: File + Value Errors

try:
filename = input("Enter file name: ")
lines = open(filename).readlines()
number = int(lines[0])
except FileNotFoundError:
print("File does not exist.")
except ValueError:
print("First line must contain a number.")

⭐ Example 3: Handling Key Errors in Dictionary

try:
student = {"name": "Alex", "age": 20}
print(student["grade"])
except KeyError:
print("Grade information is missing in the record.")

------------------------------------------

🟧 3. Using else with try-except

------------------------------------------

else runs only if no exception occurs.


⭐ Example 1: Clean Division

try:
x = 5
y = 2
result = x / y
except ZeroDivisionError:
print("Error!")
else:
print("Division successful:", result)

⭐ Example 2: File Read Success

try:
file = open("notes.txt")
except FileNotFoundError:
print("File missing.")
else:
print("File opened successfully.")
print(file.read())

⭐ Example 3: Valid User Input

try:
age = int(input("Enter your age: "))
except ValueError:
print("Invalid input.")
else:
print("Thank you! Your age is recorded.")

-------------------------------------------

🟫 4. Using finally for Cleanup

-------------------------------------------

finally always runs, even if an error happens. Useful for:

✔ closing files ✔ closing database connections ✔ freeing resources


⭐ Example 1: Closing a File

try:
f = open("sample.txt")
print(f.read())
except FileNotFoundError:
print("No file found.")
finally:
print("Closing file (if opened).")

⭐ Example 2: Safe Division with Cleanup Message

try:
print(10 / 0)
except ZeroDivisionError:
print("Oops! Division error.")
finally:
print("Process completed.")

⭐ Example 3: Database Cleanup Simulation

try:
print("Connecting to database...")
raise Exception("Connection failed")
except Exception as e:
print("Error:", e)
finally:
print("Closing database connection...")

-------------------------------------------

🔶 5. Why Is Exception Handling Important?

-------------------------------------------

Exception handling is essential because:

✔ Prevents your program from crashing

Errors become manageable instead of fatal.

✔ Makes your code professional and user-friendly

Programs show helpful messages instead of ugly crash logs.

✔ Helps in debugging

You can catch specific errors and fix them easily.

✔ Required in real-world systems

Every robust app (Banking, AI, Games, Websites) uses exception handling.

✔ Common interview topic

Companies expect you to explain and write try-except code.


-------------------------------------------

🔷 6. How to Remember for Exams & Interviews

-------------------------------------------

💡 Memory Trick 1: T-E-E-F

  • Try → code that might break
  • Except → handle the error
  • Else → runs when everything goes well
  • Finally → always runs

💡 Memory Trick 2: “Try your best, Accept your mistakes”

Try → run risky code Except → catch mistakes

💡 Memory Trick 3: Error Flow Diagram

Error? → except No error? → else Always run → finally

💡 Practice Tip

Write 5 small programs daily that intentionally cause errors (ZeroDivision, file errors, input errors).