--------------- <> -----------------
--- 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: