Bài tập Exception Handling - Cơ bản
- Viết chương trình nhập một số từ người dùng. Nếu người dùng nhập sai, hiển thị thông báo lỗi và yêu cầu nhập lại.
try: number = int(input("Nhập một số: ")) print(f"Bạn đã nhập: {number}")except ValueError: print("Vui lòng nhập một số hợp lệ!")- Viết hàm
safe_dividethực hiện phép chia an toàn (xử lý chia cho 0).
def safe_divide(a, b): # Code của bạn ở đây pass
# Testprint(safe_divide(10, 2)) # 5.0print(safe_divide(10, 0)) # "Không thể chia cho 0!"- Viết hàm
get_list_itemlấy phần tử từ list theo index, xử lý lỗi nếu index không hợp lệ.
def get_list_item(my_list, index): # Code của bạn ở đây pass
# Testnumbers = [1, 2, 3, 4, 5]print(get_list_item(numbers, 2)) # 3print(get_list_item(numbers, 10)) # "Index không hợp lệ!"- Viết hàm
get_dict_valuelấy giá trị từ dictionary theo key, xử lý lỗi nếu key không tồn tại.
def get_dict_value(my_dict, key): # Code của bạn ở đây pass
# Teststudent = {"name": "Alice", "age": 20}print(get_dict_value(student, "name")) # "Alice"print(get_dict_value(student, "grade")) # "Key không tồn tại!"- Viết hàm
safe_convert_to_intchuyển đổi chuỗi thành số nguyên, trả về 0 nếu không thể chuyển đổi.
def safe_convert_to_int(text): # Code của bạn ở đây pass
# Testprint(safe_convert_to_int("123")) # 123print(safe_convert_to_int("abc")) # 0- Viết chương trình mở và đọc file. Xử lý lỗi nếu file không tồn tại.
try: # Code của bạn ở đây passexcept FileNotFoundError: print("File không tồn tại!")- Viết hàm
calculatethực hiện phép tính từ chuỗi (dùng eval), xử lý các lỗi có thể xảy ra.
def calculate(expression): # Code của bạn ở đây pass
# Testprint(calculate("2 + 3")) # 5print(calculate("10 / 0")) # "Lỗi: không thể chia cho 0"print(calculate("2 + abc")) # "Lỗi: biến không xác định"- Viết hàm
get_agenhập tuổi từ người dùng, yêu cầu nhập lại nếu không hợp lệ (dùng vòng lặp).
def get_age(): while True: try: # Code của bạn ở đây pass except ValueError: print("Vui lòng nhập số!")
# Testage = get_age()print(f"Tuổi: {age}")- Viết hàm
try_except_elseminh họa cách dùng try/except/else.
def try_except_else(number): try: result = 100 / number except ZeroDivisionError: print("Không thể chia cho 0") else: print(f"Kết quả: {result}")
# Testtry_except_else(10) # "Kết quả: 10.0"try_except_else(0) # "Không thể chia cho 0"- Viết hàm
try_finallyminh họa cách dùng try/finally (finally luôn chạy).
def try_finally(): try: print("Đang xử lý...") result = 10 / 0 except ZeroDivisionError: print("Có lỗi!") finally: print("Cleanup - Luôn chạy")
# Testtry_finally()- Viết hàm
safe_list_accesstruy cập list an toàn, trả về giá trị mặc định nếu lỗi.
def safe_list_access(my_list, index, default=None): # Code của bạn ở đây pass
# Testnumbers = [1, 2, 3]print(safe_list_access(numbers, 1)) # 2print(safe_list_access(numbers, 10)) # Noneprint(safe_list_access(numbers, 10, 0)) # 0- Viết hàm
parse_int_listchuyển list chuỗi thành list số, bỏ qua các giá trị không hợp lệ.
def parse_int_list(string_list): # Code của bạn ở đây pass
# Teststrings = ["1", "2", "abc", "3", "xyz", "4"]print(parse_int_list(strings)) # [1, 2, 3, 4]- Viết hàm
safe_averagetính trung bình list, xử lý list rỗng.
def safe_average(numbers): # Code của bạn ở đây pass
# Testprint(safe_average([1, 2, 3, 4, 5])) # 3.0print(safe_average([])) # "List rỗng!"- Viết chương trình nhập 2 số và thực hiện phép chia, xử lý cả lỗi nhập liệu và chia cho 0.
try: # Code của bạn ở đây passexcept ValueError: print("Vui lòng nhập số!")except ZeroDivisionError: print("Không thể chia cho 0!")- Viết hàm
get_file_contentđọc nội dung file, trả về None nếu file không tồn tại.
def get_file_content(filename): # Code của bạn ở đây pass
# Testcontent = get_file_content("data.txt")if content: print(content)- Viết hàm
multiple_exceptionsxử lý nhiều loại exception cùng lúc.
def multiple_exceptions(data, index): try: result = int(data[index]) return result / 2 except (IndexError, ValueError, TypeError) as e: return f"Lỗi: {e}"
# Testprint(multiple_exceptions([1, 2, 3], 1)) # 1.0print(multiple_exceptions([1, 2, 3], 10)) # "Lỗi: ..."print(multiple_exceptions(["a", "b"], 0)) # "Lỗi: ..."- Viết hàm
raise_custom_errortạo và ném exception với thông báo tùy chỉnh.
def check_positive(number): if number < 0: raise ValueError("Số phải là số dương!") return number
# Testtry: check_positive(-5)except ValueError as e: print(f"Lỗi: {e}")- Viết hàm
safe_dict_updatecập nhật dictionary, bắt TypeError nếu key không phải string.
def safe_dict_update(my_dict, key, value): try: if not isinstance(key, str): raise TypeError("Key phải là string!") my_dict[key] = value return True except TypeError as e: print(f"Lỗi: {e}") return False
# Testdata = {}safe_dict_update(data, "name", "Alice") # Truesafe_dict_update(data, 123, "value") # False- Viết chương trình menu đơn giản với exception handling cho lựa chọn không hợp lệ.
while True: print("\n1. Option 1") print("2. Option 2") print("3. Thoát")
try: choice = int(input("Chọn: ")) if choice == 3: break elif choice in [1, 2]: print(f"Bạn chọn option {choice}") else: print("Lựa chọn không hợp lệ!") except ValueError: print("Vui lòng nhập số!")- Viết hàm
exception_loggerghi lại thông tin lỗi vào file log.
def exception_logger(func): def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: with open("error.log", "a") as log: log.write(f"Error: {e}\n") raise
return wrapper
# Test@exception_loggerdef risky_function(): return 10 / 0
try: risky_function()except: print("Lỗi đã được ghi log")