Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
In Python, try and except blocks catch runtime errors (called exceptions) so your program handles invalid input or missing files gracefully instead of crashing with a traceback. You place risky code inside try:, and write recovery instructions inside one or more except ErrorType: blocks.
Up to now, if a user typed "abc" when your calculator expected a number—or if your script tried to open a file that did not exist—Python immediately terminated the program. Real-world projects (like the Contact Book, Quiz App, and Expense Tracker in Chapter 16) rely on try/except to stay reliable.
Before writing try/except, understand the difference between the two kinds of errors in Python:
| Error Category | When It Happens | Can try/except Catch It? | Example |
|---|---|---|---|
| Syntax Error | Before the program runs (parsing stage) | No — must fix the code | if x == 5 print(x) (missing :) |
| Runtime Exception | While valid Python code is executing | Yes — catch with try/except | 10 / 0 (ZeroDivisionError), int("hi") (ValueError) |
try / except SyntaxHow execution flows:
19, the try block succeeds and the except block is completely skipped.nineteen, int("nineteen") raises a ValueError, execution jumps immediately to except ValueError:, and the program finishes cleanly without crashing.Always catch the specific exception you expect rather than catching everything blindly. Here are the 5 most common exceptions in beginner projects:
| Exception Type | Common Trigger | Example |
|---|---|---|
ValueError | Right type, invalid value | int("hello") |
ZeroDivisionError | Dividing or modulo by zero | 100 / 0 |
FileNotFoundError | Opening a missing file in 'r' mode | open("missing.txt", "r") |
KeyError | Looking up a missing dictionary key | student["grade"] |
IndexError | Accessing an out-of-range list index | items[10] on a 3-item list |
try/except with File Handling (with open())File operations are one of the top places where runtime exceptions happen because external files can be moved, renamed, or deleted.
Notice how using with open(...) guarantees the file is closed automatically, while except FileNotFoundError: gives first-time users a smooth experience instead of a scary red traceback.
except: Clausestry Block Small and FocusedOnly wrap the lines that can actually raise the expected exception. Wrapping 50 lines of unrelated code in a single try: block makes debugging much harder.
while LoopA classic CLI pattern combines while True: with try/except to re-prompt until valid input arrives:
safe_divide(a, b) that returns None and prints a friendly message if b == 0.with open(), and handles FileNotFoundError gracefully.1. Add Contact, 2. View Contacts, 3. Exit) that keeps asking until the user enters 1, 2, or 3 without ever crashing on letters or symbols.try block completes with NO exceptions?"r") mode?finally block execute?except: without specifying an exception type?int("25a") runs inside a try block with except ValueError:?With file handling and error handling under your belt, you are ready to build real portfolio projects in Chapter 16—starting with Project 1: Contact Book →!
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| File Methods (read, readline, write) | Contact Book |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Go beyond self-study with 46 chapters, 236 practical topics, 14 portfolio projects, code reviews, and a verifiable certificate at MSK Institute Shikohabad or Live Online.