Exceptions · Ngoại lệ
When things go wrong
- A runtime error normally crashes the program.
- An exception is Python's signal that something went wrong.
- Exception handling lets you catch it and keep running.
Khi sự cố xảy ra
- Lỗi thời gian chạy thường làm crash (sập) chương trình.
- Một exception (ngoại lệ) là tín hiệu của Python cho thấy điều gì đó đã sai.
- Xử lý ngoại lệ cho phép bạn bắt nó và tiếp tục chạy.
try / except
- Put risky code in a
try:block. - If it raises an exception, the
except:block runs instead of crashing. - If nothing goes wrong, the
exceptblock is skipped.
try / except
- Đặt đoạn mã rủi ro vào trong khối
try:. - Nếu nó gây ra ngoại lệ, khối
except:sẽ chạy thay vì sập. - Nếu mọi thứ ổn, khối
exceptsẽ bị bỏ qua.
try:
number = int("not a number")
except ValueError:
number = 0
print(number)
Catch the right error
- Name the type of error you expect:
except ValueError:. ValueErroris bad text for a number;ZeroDivisionErroris divide by zero.- Catching a specific type means you do not hide other bugs.
Bắt đúng lỗi
- Đặt tên loại lỗi bạn mong đợi:
except ValueError:. ValueErrorlà văn bản kém cho một con số;ZeroDivisionErrorlà phép chia cho không.- Bắt một loại cụ thể có nghĩa là bạn không che giấu các lỗi khác.
try:
print(10 / 0)
except ZeroDivisionError:
print("Cannot divide by zero")
finally and raise
- A
finally:block always runs, error or not — good for cleanup. raiselets you signal an error on purpose.raise ValueError("message")stops the code unless something catches it.
finally và raise
- Một khối
finally:luôn chạy, dù có hay không có lỗi — tốt cho việc dọn dẹp. raisecho phép bạn báo hiệu lỗi một cách chủ đích.raise ValueError("message")dừng mã trừ khi có thứ gì đó bắt lấy nó.
try:
raise ValueError("bad value")
except ValueError as e:
print("Caught:", e)
finally:
print("Always runs")
Why it matters
- A robust program should not crash on bad input.
- Handling exceptions lets it warn the user and carry on.
- It also makes sure files and other resources are closed cleanly.
Tại sao điều đó quan trọng
- Một chương trình mạnh mẽ không nên sập do đầu vào kém.
- Xử lý ngoại lệ cho phép nó cảnh báo người dùng và tiếp tục.
- Nó cũng đảm bảo các tệp và tài nguyên khác được đóng gọn gàng.
Common mistakes
- Catch a specific error (
except ValueError:), not a bareexcept:. - Put only the risky line inside the
try.
Lỗi thường gặp
- Bắt một lỗi cụ thể (
except ValueError:), không phải mộtexcept:trần. - Chỉ đặt dòng rủi ro bên trong khối
try.
Now you try
- Use
try/except(andraisein the last task). - Press Check answer to test your code.
Bây giờ bạn thử
- Dùng
try/except(vàraisetrong bài tập cuối). - Nhấn Check answer (Kiểm tra câu trả lời) để thử mã của bạn.
try / except
Code runs in try; if it fails, control jumps to except. · Code chạy trong try; nếu thất bại, điều khiển nhảy sang except.
Write safe_int(text) that returns int(text). If the text is not a valid number, catch the ValueError and return -1 instead. · Viết safe_int(text) trả về int(text). Nếu văn bản không phải là số hợp lệ, bắt ngoại lệ ValueError và trả về -1 thay thế.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
Write divide(a, b) that returns a / b. If b is 0, catch the ZeroDivisionError and return None instead. · Viết divide(a, b) trả về a / b. Nếu b bằng 0, bắt ngoại lệ ZeroDivisionError và trả về None thay thế.
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
Write withdraw(balance, amount). If amount is more than balance, raise ValueError. Otherwise return the new balance (balance - amount). · Viết withdraw(balance, amount). Nếu amount lớn hơn balance, thì raise ValueError. Ngược lại trả về số dư mới (balance - amount).
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.