--------------- <> -----------------
--- KHOA HỌC - CÔNG NGHỆ - GIÁO DỤC - VIỆC LÀM ---
--- Học để đi cùng bà con trên thế giới ---

Tìm kiếm trong Blog

Python (25) - Xử lý ngoại lệ với try ... except

Bài trước: Python (24) - Bài tập thao tác với tập tin văn bản
-----

25. Xử lý ngoại lệ với Try ... Except

Trong quá trình viết chương trình, ngoài những lỗi về cú pháp (syntax error) làm chương trình không thể chạy ngay từ đầu, bạn sẽ gặp phải những lỗi xuất hiện khi chương trình đang chạy, được gọi là ngoại lệ (exception) hoặc lỗi runtime.

Ví dụ, khi bạn yêu cầu người dùng nhập một số nguyên, nhưng họ lại nhập vào chữ cái, hoặc khi chương trình thực hiện phép chia cho số 0, hay mở một tập tin không tồn tại. Nếu không được xử lý, chương trình sẽ lập tức bị ngừng đột ngột và hiển thị dòng báo lỗi.

Để chương trình hoạt động mượt mà, chuyên nghiệp và không bị dừng đột ngột khi gặp lỗi, Python cung cấp cấu trúc try ... except.

25.1 Cấu trúc cơ bản của try ... except

Cấu trúc try ... except hoạt động theo cơ chế "thử và bắt lỗi":

- try: Khối lệnh chứa các câu lệnh có nguy cơ phát sinh lỗi khi chạy

- except: Khối lệnh sẽ được kích hoạt và thực thi nếu có lỗi phát sinh trong khối try

Cú pháp:

try:

    # Khối lệnh thực thi (có nguy cơ xảy ra lỗi)

    câu_lệnh_1

    câu_lệnh_2

except:

    # Khối lệnh xử lý khi có lỗi xuất hiện trong khối try

    xử_lý_khi_gặp_lỗi

25.2 Bắt các loại ngoại lệ cụ thể

Một khối try có thể phát sinh nhiều loại lỗi khác nhau. Việc bắt đúng từng loại lỗi giúp bạn đưa ra thông báo chính xác cho người dùng.

Một số lỗi phổ biến trong Python:

- ValueError: Lỗi giá trị, ví dụ: ép kiểu chuỗi "abc" sang số nguyên int("abc")

- ZeroDivisionError: Lỗi chia cho số 0

- FileNotFoundError: Lỗi không tìm thấy tập tin

- TypeError: Lỗi do thao tác trên kiểu dữ liệu không phù hợp

Ví dụ, bạn hãy lập trình và chạy đoạn mã sau:

try:

    so_a = int(input("Nhập số bị chia: "))

    so_b = int(input("Nhập số chia: "))

    ket_qua = so_a / so_b

    print(f"Kết quả {so_a} / {so_b} = {ket_qua}")

except ValueError:

    print("Lỗi: Bạn phải nhập vào một số nguyên hợp lệ!")


except ZeroDivisionError:

    print("Lỗi: Không thể thực hiện phép chia cho số 0!")

except Exception as e:

    # Bắt tất cả các loại lỗi còn lại chưa dự đoán trước

    print(f"Đã xảy ra lỗi không xác định: {e}")

Bạn hãy chạy chương trình trên và nhập vào giá trị theo các tình huống sau, để quan sát các lỗi:

[Tình huống 1]: chương trình chạy bình thường

- Số bị chia: 10

- Số chia: 5

[Tình huống 2]: lỗi chia cho số 0

- Số bị chia: 10

- Số chia: 0

[Tình huống 3]: lỗi ép kiểu từ chuỗi thành số

- Số bị chia: 10

- Số chia: abc

25.3 Sử dụng Else và Finally

Python cho phép bổ sung thêm hai khối lệnh else và finally cho try … except:

- else: Chạy khi khối try thực thi thành công và không phát sinh bất kỳ lỗi nào

- finally: Luôn luôn chạy dù chương trình có xảy ra lỗi hay không. Thường dùng để giải phóng tài nguyên (như đóng tập tin, đóng kết nối cơ sở dữ liệu)

Bạn hãy viết đoạn mã thao tác với tập tin:

try:

    f = open("du_lieu.txt", "r", encoding="utf-8")

except FileNotFoundError:

    print("Lỗi: Tập tin 'du_lieu.txt' không tồn tại trên hệ thống!")

else:

    # Khối lệnh này chỉ chạy khi mở file thành công

    noi_dung = f.read()

    print("Nội dung tập tin:")

    print(noi_dung)

    f.close()

finally:

    print("Hoàn tất quá trình xử lý tập tin.")

Chạy tập tin theo các tình huống sau:

[Tình huống 1]: lỗi không có tập tin

- Bạn chạy tập tin mã nguồn, nhưng chưa tạo tập tin du_lieu.txt

[Tình huống 2]: chương trình chạy không có lỗi

- Bạn chạy tập tin mã nguồn, tạo tập tin du_lieu.txt, tập tin du_lieu.txt có dữ liệu (ví dụ: chao ban Teo). Lưu ý: tập tin du_lieu.txt phải cùng thư mục với tập tin mã nguồn.

25.4 Bài tập và câu hỏi

Bài tập 

Bài 25a: Nhập số an toàn cho Máy tính cầm tay

Mục tiêu: Đảm bảo chương trình không bị dừng đột ngột khi người dùng nhập dữ liệu sai.

Yêu cầu: Viết đoạn mã dùng vòng lặp while kết hợp try ... except để yêu cầu người dùng nhập vào một số thực. Nếu người dùng nhập sai (ví dụ nhập chữ "abc"), chương trình phải thông báo lỗi và yêu cầu nhập lại cho đến khi nhận được một số thực hợp lệ.

Bài 25b: Chia an toàn

Mục tiêu: Thực hành bắt nhiều ngoại lệ trong bài toán thực tế.

Yêu cầu: Viết chương trình máy tính thực hiện phép chia hai số ab nhập từ bàn phím. Sử dụng try ... except để xử lý triệt để hai trường hợp lỗi:

1. Người dùng nhập ký tự không phải là số (ValueError)

2. Số chia b=0 (ZeroDivisionError)

In kết quả phép tính ra màn hình nếu không có lỗi xảy ra.

Bài 25c: Nhật ký tính toán và Đọc dữ liệu lịch sử

Mục tiêu: Kết hợp try ... except với thao tác làm việc trên tập tin văn bản.

Yêu cầu: Viết chương trình mở tập tin lich_su_may_tinh.txt để đọc lịch sử các phép tính, xuất ra màn hình. Dùng try ... except để xử lý trường hợp tập tin chưa tồn tại (chương trình sẽ thông báo: "Chưa có lịch sử tính toán nào được lưu!" thay vì dừng chương trình và báo lỗi).

Câu hỏi

Câu 25.1: Khối lệnh nào trong cấu trúc try ... except sẽ luôn luôn được thực thi dù chương trình có phát sinh lỗi hay không?

A. try

B. except

C. else

D. finally

Câu 25.2: Khi thực hiện phép tính x = 10 / 0, Python sẽ phát sinh loại ngoại lệ (Exception) nào sau đây?

A. ValueError

B. ZeroDivisionError

C. IndexError

D. FileNotFoundError

Câu 25.3: Cho đoạn mã sau:

try:

    val = int("123a")

    print("Chuyển đổi thành công!")

except ValueError:

    print("Lỗi chuyển đổi dữ liệu!")

else:

    print("Thực thi thành công!")

Kết quả in ra màn hình là gì?

A. Chuyển đổi thành công!

B. Lỗi chuyển đổi dữ liệu!

C. Thực thi thành công!

D. Lỗi chuyển đổi dữ liệu! / Thực thi thành công!

Here is the complete English translation of your text, using standard programming terminology (Python conventions, standard identifier naming, and accurate terms like runtime errors, type casting, exceptions, and resource cleanup).

25. Exception Handling with Try ... Except

In addition to syntax errors that prevent a program from executing from the start, you will also encounter errors that occur while the program is running. These are called exceptions or runtime errors.

For example, when you ask a user to enter an integer but they enter text, when a program attempts to divide by zero, or when opening a non-existent file. If left unhandled, these errors cause the program to crash immediately and display an error trace.

To keep your program running smoothly and professionally without sudden crashes when encountering errors, Python provides the try ... except structure.

25.1 Basic Structure of try ... except

The try ... except construct operates on a "try and catch" mechanism:

- try: A block containing code statements that risk throwing an error during execution

- except: A block triggered and executed only if an error occurs inside the try block

Syntax:

try:

    # Code block to execute (risks raising an error)

    statement_1

    statement_2

except:

    # Code block to handle errors raised in the try block

    handle_error

25.2 Handling Specific Exception Types

A single try block can raise various types of errors. Catching specific exception types allows you to provide accurate error messages to the user.

Common Built-in Exceptions in Python:

- ValueError: Raised when a function receives an argument of the correct type but an inappropriate value (e.g., type casting a string "abc" to an integer: int("abc"))

- ZeroDivisionError: Raised when dividing a number by zero

- FileNotFoundError: Raised when trying to access a file that does not exist

- TypeError: Raised when an operation is applied to an inappropriate data type

Example Code:

try:

    dividend = int(input("Enter dividend: "))

    divisor = int(input("Enter divisor: "))

    result = dividend / divisor

    print(f"Result: {dividend} / {divisor} = {result}")

except ValueError:

    print("Error: You must enter a valid integer!")

except ZeroDivisionError:

    print("Error: Division by zero is not allowed!")

except Exception as e:

    # Catch any other unexpected errors

    print(f"An unexpected error occurred: {e}")

Run the program and test the following scenarios to observe error handling:

[Scenario 1]: Normal Execution

- Dividend: 10

- Divisor: 5

[Scenario 2]: Division by Zero Error

- Dividend: 10

- Divisor: 0

[Scenario 3]: Type Casting Error

- Dividend: 10

- Divisor: abc

25.3 Using else and finally

Python allows extending try ... except with else and finally clauses:

- else: Executes only if the try block succeeds without raising any exceptions

- finally: Always executes regardless of whether an error occurred. Commonly used for resource cleanup (e.g., closing file streams, releasing database connections).

Example Code:

try:

    f = open("data.txt", "r", encoding="utf-8")

except FileNotFoundError:

    print("Error: The file 'data.txt' does not exist on the system!")

else:

    # Executes only if the file opened successfully

    content = f.read()

    print("File Content:")

    print(content)

    f.close()

finally:

    print("File processing complete.")

Run the program under the following conditions:

[Scenario 1]: File Not Found Error

- Run the script without creating data.txt

[Scenario 2]: Successful Execution

- Create data.txt with content (e.g., "Hello World") in the same directory as the script, then run it.

25.4 Exercises and Questions

Exercises

Exercise 25a: Safe Input for Handheld Calculator

- Goal: Prevent abrupt program termination on invalid user input

- Requirement: Write a program using a while loop combined with try ... except to prompt the user to enter a float. If the input is invalid (e.g., entering "abc"), print an error message and re-prompt until a valid float is provided

Exercise 25b: Safe Division

- Goal: Practice handling multiple exceptions in a practical context

- Requirement: Write a calculator script that performs division of two numbers, a and b, entered from the keyboard. Use try ... except to fully handle two error cases:

  + User inputs non-numeric characters (ValueError)

    + Divisor b=0 (ZeroDivisionError)

    + Print the calculation result if no errors occur

Exercise 25c: Calculation Log & History Reader

- Goal: Combine try ... except with file handling

- Requirement: Write a program to open calculator_history.txt, read previous calculation logs, and display them on screen. Use try ... except to handle cases where the file does not exist yet (print "No calculation history found!" instead of throwing an error and crashing)

Quiz Questions

Question 25.1: Which block in a try ... except structure always executes, regardless of whether an exception occurred?

A. try

B. except

C. else

D. finally

Question 25.2: What exception type does Python raise when executing x = 10 / 0?

A. ValueError

B. ZeroDivisionError

C. IndexError

D. FileNotFoundError

Question 25.3: Consider the following code snippet:

try:

    val = int("123a")

    print("Conversion successful!")

except ValueError:

    print("Data conversion error!")

else:

    print("Executed successfully!")

What is the output displayed on the console?

A. Conversion successful!

B. Data conversion error!

C. Executed successfully!

D. Data conversion error! / Executed successfully!

-----
Bài sau:

Python (24) - Bài tập thao tác với tập tin văn bản

Bài trước: Python (23) - Thao tác với tập tin văn bản
-----

24. Bài tập thao tác với tập tin văn bản

Ở bài học trước, bạn đã được học cách thao tác với tập tin văn bản. Để giúp bạn rèn luyện thêm, bài học này bao gồm các bài tập để bạn thực hành. Làm nhiều thì sẽ quen tay, nghĩ nhiều thì quen não. Bạn hãy tự nghĩ ra cách làm, viết giải thuật ra giấy, và gõ từng dòng mã để giúp nâng cao khả năng tư duy của bạn.

24.1 Thao tác với tập tin .txt

Yêu cầu:

Với mỗi bài tập, bạn bắt buộc phải làm các công việc sau:

- Viết lại các bước của quá trình làm bài, các câu hỏi đã hỏi AI, các câu lệnh lập trình, ý nghĩa của từng câu lệnh (để học về kỹ năng trình bày, tư duy logic, và kỹ năng đặt câu hỏi cho AI)

- Xem phần trình bày mẫu của Bài 24a

Bài 24a: Đếm số từ

Cho tập tin van_ban.txt chứa một đoạn văn tiếng Việt không dấu. Hãy viết chương trình:

- Đọc nội dung từ tập tin

- Đếm xem trong đoạn văn có bao nhiêu từ (các từ cách nhau bằng khoảng trắng)

- Ghi kết quả vào tập tin ket_qua.txt

Các bước thực hiện

[Bước 1] Bạn cần sử dụng chương trình Notepad để tạo tập tin van_ban.txt, nhập nội dung cho tập tin này. Ví dụ, nhập nội dung là: Hoc bai ban > lam chuyen nghiep > song hanh phuc

[Bước 2] Lập trình

- Mở tập tin bằng hàm: 

f = open("van_ban.txt", "r", encoding="utf-8")

- Đọc nội dung tập tin, lưu vào một biến, xuất nội dung của biến để kiểm tra xem việc đọc tập tin được chưa?

str = f.read()

print(str)

- Câu hỏi cho AI: trong python, làm sao để đếm số từ của một chuỗi văn bản

- Để đếm từ trong một chuỗi văn bản: sử dụng hàm split() để loại bỏ khoảng trắng thừa và cắt từ dựa trên khoảng trắng, lưu vào danh sách > đếm số phần tử của danh sách bằng hàm len()

words = str.split()

word_count = len(words)

- Xuất kết quả để kiểm tra

print(f"So tu la: {word_count}")

- Ghi kết quả ra tập tin ketqua.txt

(bạn tự làm tiếp ...)

Bài 24b: Tìm số lớn nhất

Cho tập tin day_so.txt gồm nhiều dòng (tối thiểu 10 dòng), mỗi dòng chứa một số nguyên.

- Đọc toàn bộ các số nguyên trong tập tin

- Tìm số lớn nhất và số nhỏ nhất trong dãy số đó

- Ghi dòng chữ "Số lớn nhất là: ..." và "Số nhỏ nhất là: ..." vào tập tin thong_ke.txt

Bài 24c: Kiểm tra số nguyên tố

Cho tập tin input.txt chứa một số nguyên dương n

- Đọc giá trị n từ tập tin

- Kiểm tra xem n có phải là số nguyên tố hay không

- Nếu là số nguyên tố, ghi "YES" vào tập tin output.txt. Ngược lại ghi "NO"

24.2 Bài tập về tập tin CSV

Tập tin CSV thường được dùng để quản lý danh sách có cấu trúc cột rõ ràng, giống như quản lý học sinh hoặc kho hàng.

Bài 24d: Quản lý thư viện

Tạo danh sách gồm 3 cuốn sách bạn yêu thích (Tên sách, Tác giả).

- Ghi danh sách này vào tập tin thu_vien.csv

- Viết chương trình đọc lại tập tin này và in ra màn hình theo định dạng: "Cuốn sách [Tên sách] được viết bởi [Tác giả]".

Bài 24e: Tính điểm trung bình

Cho tập tin bang_diem.csv có cấu trúc: Tên,Toán,Văn. 

Ví dụ: 

[bang_diem.csv]

Tên,Toán,Văn 

Nguyen Van An,8,9 

Le Thi Binh,10,7 

Tran Huu Loc,6.5,8

- Đọc dữ liệu từ tập tin

- Tính điểm trung bình (ĐTB = (Toán + Văn) / 2) cho từng học sinh

- Ghi thêm một cột "Trung Bình" vào tập tin mới đặt tên là ket_qua_hoc_tap.csv.

Bài 24f: Lọc dữ liệu 

Cho tập tin san_pham.csv chứa danh sách hàng hóa: Tên SP,Giá Tiền.

Ví dụ:

[san_pham.csv]

Tên SP,Giá Tiền 

Chuột máy tính,250000 

Bàn phím cơ,850000 

Tai nghe,450000

Lót chuột,100000 

Loa Bluetooth,1200000

- Viết chương trình yêu cầu người dùng nhập vào một mức giá ngân sách (ví dụ: 500.000)

- Tìm và liệt kê tất cả các sản phẩm có giá thấp hơn hoặc bằng mức ngân sách đó

- Lưu danh sách các sản phẩm thỏa mãn vào tập tin mua_sam.csv

24. Exercise with Text Files

In the previous lesson, you learned how to work with text files. To help you practice further, this lesson includes hands-on exercises. Practice builds muscle memory, and active thinking sharpens the mind. Try to figure out the solutions on your own, write the algorithms on paper, and type out every line of code to enhance your computational thinking skills. 

24.1 Working with .txt Files

Requirements

For every exercise, you must complete the following steps:

- Document your step-by-step process, the prompts/questions you asked AI, the code snippets, and the explanation of each line of code (to develop documentation skills, logical reasoning, and effective AI prompting skills)

- Refer to the sample layout in Task 24a

Task 24a: Word Count

Given a file named van_ban.txt containing unaccented Vietnamese text, write a program to:

- Read the content from the file

- Count the total number of words in the text (words are separated by spaces)

- Write the output to a file named ket_qua.txt

Execution Steps

[Step 1]: Use Notepad (or any text editor) to create van_ban.txt and enter sample content.
Example content: Hoc bai ban > lam chuyen nghiep > song hanh phuc

[Step 2]: Coding

- Open the file using:

f = open("van_ban.txt", "r", encoding="utf-8")

- Read the file content into a variable and print it out to verify the file reading step:

str = f.read()

print(str)

- Prompt asked the AI: "How to count the number of words in a text string in Python?"

- Use the split() method to strip excess whitespace and split the string into words based on spaces, storing them in a list. Then, count the number of elements using len().

words = str.split()

word_count = len(words)

- Output the result:

print(f"So tu la: {word_count}")

- Write the results to the ketqua.txt file

(Complete the rest on your own...)

Task 24b: Find Maximum and Minimum

Given a file named day_so.txt with multiple lines (at least 10 lines), where each line contains an integer:

- Read all integers from the file

- Find the maximum and minimum values in the dataset

- Write "The maximum value is:...” and "The minimum value is: …” to a file named thong_ke.txt

Task 24c: Prime Number Check

Given a file named input.txt containing a positive integer n:

- Read the value of n from the file

- Check whether n is a prime number

- If it is a prime number, write "YES" to output.txt. Otherwise, write "NO"

24.2 CSV File Exercises

CSV files are commonly used to handle structured tabular data, such as student records or inventory management.

Task 24d: Library Management

Create a list containing 3 of your favorite books (Book Title, Author)

- Export/write this list to a file named thu_vien.csv

- Write a program to read this file back and display the output in the format:
"The book [Book Title] was written by [Author]”

Task 24e: Calculate Average Score

Given a file named bang_diem.csv with the structure: Name, Math, Literature.

Example (bang_diem.csv):

Name, Math, Literature

Nguyen Van An, 8, 9

Le Thi Binh, 10, 7

Tran Huu Loc, 6.5, 8

- Read data from the file

- Calculate the average score GPA = (Math + Literature)/2 for each student

- Append a new column named "Average" and save the output to a new file named ket_qua_hoc_tap.csv.

Task 24f: Data Filtering

Given a file named san_pham.csv containing a product inventory list: Product Name, Price.

Example (san_pham.csv):

Product Name, Price

Computer Mouse, 250000

Mechanical Keyboard, 850000

Headphones, 450000

Mousepad, 100000

Bluetooth Speaker, 1200000

- Write a program that prompts the user to enter a budget limit (e.g., 500000)

- Filter and display all products with a price less than or equal to the entered budget

- Save the filtered result set into a file named mua_sam.csv

-----