Tóm lược. trong hướng dẫn này, bạn sẽ học cách sử dụng câu lệnh
9 của Python để xử lý ngoại lệ một cách khéo léoCode language: Shell Session [shell]
File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax
Trong Python, có hai loại lỗi chính. lỗi cú pháp và ngoại lệ
Lỗi cú pháp
Khi bạn viết mã Python không hợp lệ, bạn sẽ gặp lỗi cú pháp. Ví dụ
Code language: Python [python]
current = 1 if current < 10 current += 1
Nếu bạn cố chạy mã này, bạn sẽ gặp lỗi sau
Code language: Shell Session [shell]
File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax
Trong ví dụ này, trình thông dịch Python đã phát hiện lỗi tại câu lệnh
0 do dấu hai chấm [Code language: Python [python]
# get input net sales print['Enter the net sales for'] previous = float[input['- Prior period:']] current = float[input['- Current period:']] # calculate the change in percentage change = [current - previous] * 100 / previous # show the result if change > 0: result = f'Sales increase {abs[change]}%' else: result = f'Sales decrease {abs[change]}%' print[result]
1] bị thiếu sau câu lệnhCode language: Python [python]
# get input net sales print['Enter the net sales for'] previous = float[input['- Prior period:']] current = float[input['- Current period:']] # calculate the change in percentage change = [current - previous] * 100 / previous # show the result if change > 0: result = f'Sales increase {abs[change]}%' else: result = f'Sales decrease {abs[change]}%' print[result]
Trình thông dịch Python hiển thị tên tệp và số dòng xảy ra lỗi để bạn có thể khắc phục
ngoại lệ
Mặc dù khi mã của bạn có cú pháp hợp lệ, nó có thể gây ra lỗi trong quá trình thực thi
Trong Python, các lỗi xảy ra trong quá trình thực thi được gọi là ngoại lệ. Nguyên nhân của các ngoại lệ chủ yếu đến từ môi trường mà mã thực thi. Ví dụ
- Đọc một tập tin không tồn tại
- Kết nối với máy chủ từ xa đang ngoại tuyến
- Đầu vào của người dùng không hợp lệ
Khi xảy ra ngoại lệ, chương trình không tự động xử lý. Điều này dẫn đến một thông báo lỗi
Ví dụ: chương trình sau tính toán mức tăng trưởng doanh số
Code language: Python [python]
# get input net sales print['Enter the net sales for'] previous = float[input['- Prior period:']] current = float[input['- Current period:']] # calculate the change in percentage change = [current - previous] * 100 / previous # show the result if change > 0: result = f'Sales increase {abs[change]}%' else: result = f'Sales decrease {abs[change]}%' print[result]
Làm thế nào nó hoạt động
- Đầu tiên, nhắc người dùng nhập hai số. doanh thu thuần của giai đoạn trước và hiện tại
- Sau đó, tính toán mức tăng trưởng doanh số bán hàng theo tỷ lệ phần trăm và hiển thị kết quả
Khi bạn chạy chương trình và nhập
2 là doanh thu thuần của giai đoạn hiện tại, trình thông dịch Python sẽ đưa ra kết quả sauCode language: Python [python]
# get input net sales print['Enter the net sales for'] previous = float[input['- Prior period:']] current = float[input['- Current period:']] # calculate the change in percentage change = [current - previous] * 100 / previous # show the result if change > 0: result = f'Sales increase {abs[change]}%' else: result = f'Sales decrease {abs[change]}%' print[result]
Code language: Shell Session [shell]
Enter the net sales for - Prior period:100 - Current period:120' Traceback [most recent call last]: File "d:/python/try-except.py", line 5, in current = float[input['- Current period:']] ValueError: could not convert string to float: "120'"
Trình thông dịch Python đã hiển thị truy nguyên bao gồm thông tin chi tiết về ngoại lệ
- Đường dẫn đến tệp mã nguồn [
3] đã gây ra ngoại lệ
Code language: Python [python]# get input net sales print['Enter the net sales for'] previous = float[input['- Prior period:']] current = float[input['- Current period:']] # calculate the change in percentage change = [current - previous] * 100 / previous # show the result if change > 0: result = f'Sales increase {abs[change]}%' else: result = f'Sales decrease {abs[change]}%' print[result]
- Dòng mã chính xác gây ra ngoại lệ [
4]
Code language: Python [python]# get input net sales print['Enter the net sales for'] previous = float[input['- Prior period:']] current = float[input['- Current period:']] # calculate the change in percentage change = [current - previous] * 100 / previous # show the result if change > 0: result = f'Sales increase {abs[change]}%' else: result = f'Sales decrease {abs[change]}%' print[result]
- Tuyên bố gây ra ngoại lệ
5# get input net sales print['Enter the net sales for'] previous = float[input['- Prior period:']] current = float[input['- Current period:']] # calculate the change in percentage change = [current - previous] * 100 / previous # show the result if change > 0: result = f'Sales increase {abs[change]}%' else: result = f'Sales decrease {abs[change]}%' print[result]
- Loại ngoại lệ
6
Code language: Python [python]# get input net sales print['Enter the net sales for'] previous = float[input['- Prior period:']] current = float[input['- Current period:']] # calculate the change in percentage change = [current - previous] * 100 / previous # show the result if change > 0: result = f'Sales increase {abs[change]}%' else: result = f'Sales decrease {abs[change]}%' print[result]
- Thông báo lỗi.
7
Code language: Python [python]# get input net sales print['Enter the net sales for'] previous = float[input['- Prior period:']] current = float[input['- Current period:']] # calculate the change in percentage change = [current - previous] * 100 / previous # show the result if change > 0: result = f'Sales increase {abs[change]}%' else: result = f'Sales decrease {abs[change]}%' print[result]
Bởi vì
8 không thể chuyển đổi chuỗiCode language: Python [python]
# get input net sales print['Enter the net sales for'] previous = float[input['- Prior period:']] current = float[input['- Current period:']] # calculate the change in percentage change = [current - previous] * 100 / previous # show the result if change > 0: result = f'Sales increase {abs[change]}%' else: result = f'Sales decrease {abs[change]}%' print[result]
2 thành một số, trình thông dịch Python đã đưa ra một ngoại lệCode language: Python [python]
# get input net sales print['Enter the net sales for'] previous = float[input['- Prior period:']] current = float[input['- Current period:']] # calculate the change in percentage change = [current - previous] * 100 / previous # show the result if change > 0: result = f'Sales increase {abs[change]}%' else: result = f'Sales decrease {abs[change]}%' print[result]
6Code language: Python [python]
# get input net sales print['Enter the net sales for'] previous = float[input['- Prior period:']] current = float[input['- Current period:']] # calculate the change in percentage change = [current - previous] * 100 / previous # show the result if change > 0: result = f'Sales increase {abs[change]}%' else: result = f'Sales decrease {abs[change]}%' print[result]
Trong Python, các ngoại lệ có nhiều loại khác nhau như
1,Code language: Shell Session [shell]
Enter the net sales for - Prior period:100 - Current period:120' Traceback [most recent call last]: File "d:/python/try-except.py", line 5, in current = float[input['- Current period:']] ValueError: could not convert string to float: "120'"
2, v.v.Code language: Shell Session [shell]
Enter the net sales for - Prior period:100 - Current period:120' Traceback [most recent call last]: File "d:/python/try-except.py", line 5, in current = float[input['- Current period:']] ValueError: could not convert string to float: "120'"
Xử lý ngoại lệ
Để làm cho chương trình mạnh mẽ hơn, bạn cần xử lý ngoại lệ khi nó xảy ra. Nói cách khác, bạn cần bắt ngoại lệ và thông báo cho người dùng để họ khắc phục
Một cách tốt để xử lý việc này là không hiển thị những gì trình thông dịch Python trả về. Thay vào đó, bạn thay thế thông báo lỗi đó bằng một thông báo thân thiện hơn với người dùng
Để làm điều đó, bạn có thể sử dụng câu lệnh Python
9Code language: Shell Session [shell]
File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax
9Code language: Python [python]
current = 1 if current < 10 current += 1
Câu lệnh
9 hoạt động như sauCode language: Shell Session [shell]
File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax
- Các câu lệnh trong mệnh đề
5 thực hiện trước
Code language: Shell Session [shell]Enter the net sales for - Prior period:100 - Current period:120' Traceback [most recent call last]: File "d:/python/try-except.py", line 5, in current = float[input['- Current period:']] ValueError: could not convert string to float: "120'"
- Nếu không có ngoại lệ nào xảy ra, mệnh đề
6 sẽ bị bỏ qua và việc thực thi câu lệnh
Code language: Shell Session [shell]Enter the net sales for - Prior period:100 - Current period:120' Traceback [most recent call last]: File "d:/python/try-except.py", line 5, in current = float[input['- Current period:']] ValueError: could not convert string to float: "120'"
5 đã hoàn thành
Code language: Shell Session [shell]Enter the net sales for - Prior period:100 - Current period:120' Traceback [most recent call last]: File "d:/python/try-except.py", line 5, in current = float[input['- Current period:']] ValueError: could not convert string to float: "120'"
- Nếu một ngoại lệ xảy ra tại bất kỳ câu lệnh nào trong mệnh đề
5, phần còn lại của mệnh đề sẽ bị bỏ qua và mệnh đề
Code language: Shell Session [shell]Enter the net sales for - Prior period:100 - Current period:120' Traceback [most recent call last]: File "d:/python/try-except.py", line 5, in current = float[input['- Current period:']] ValueError: could not convert string to float: "120'"
6 được thực thi
Code language: Shell Session [shell]Enter the net sales for - Prior period:100 - Current period:120' Traceback [most recent call last]: File "d:/python/try-except.py", line 5, in current = float[input['- Current period:']] ValueError: could not convert string to float: "120'"
Lưu đồ sau đây minh họa câu lệnh
9Code language: Shell Session [shell]
File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax
Vì vậy, để xử lý các ngoại lệ bằng cách sử dụng câu lệnh
9, bạn đặt mã có thể gây ra ngoại lệ trong mệnh đềCode language: Shell Session [shell]
File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax
5 và mã xử lý ngoại lệ trong mệnh đềCode language: Shell Session [shell]
Enter the net sales for - Prior period:100 - Current period:120' Traceback [most recent call last]: File "d:/python/try-except.py", line 5, in current = float[input['- Current period:']] ValueError: could not convert string to float: "120'"
6Code language: Shell Session [shell]
Enter the net sales for - Prior period:100 - Current period:120' Traceback [most recent call last]: File "d:/python/try-except.py", line 5, in current = float[input['- Current period:']] ValueError: could not convert string to float: "120'"
Đây là cách bạn có thể viết lại chương trình và sử dụng câu lệnh
9 để xử lý ngoại lệCode language: Shell Session [shell]
File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax
1Code language: Python [python]
# get input net sales print['Enter the net sales for'] previous = float[input['- Prior period:']] current = float[input['- Current period:']] # calculate the change in percentage change = [current - previous] * 100 / previous # show the result if change > 0: result = f'Sales increase {abs[change]}%' else: result = f'Sales decrease {abs[change]}%' print[result]
Nếu bạn chạy lại chương trình và nhập doanh thu ròng không phải là số, thay vào đó, chương trình sẽ đưa ra thông báo mà bạn đã chỉ định trong khối
6Code language: Shell Session [shell]
Enter the net sales for - Prior period:100 - Current period:120' Traceback [most recent call last]: File "d:/python/try-except.py", line 5, in current = float[input['- Current period:']] ValueError: could not convert string to float: "120'"
3Code language: Python [python]
# get input net sales print['Enter the net sales for'] previous = float[input['- Prior period:']] current = float[input['- Current period:']] # calculate the change in percentage change = [current - previous] * 100 / previous # show the result if change > 0: result = f'Sales increase {abs[change]}%' else: result = f'Sales decrease {abs[change]}%' print[result]
Bắt ngoại lệ cụ thể
Khi nhập doanh thu thuần của giai đoạn trước bằng 0, bạn sẽ nhận được thông báo sau
4Code language: Python [python]
# get input net sales print['Enter the net sales for'] previous = float[input['- Prior period:']] current = float[input['- Current period:']] # calculate the change in percentage change = [current - previous] * 100 / previous # show the result if change > 0: result = f'Sales increase {abs[change]}%' else: result = f'Sales decrease {abs[change]}%' print[result]
Trong trường hợp này, cả doanh thu thuần của kỳ trước và hiện tại đều là số, nhưng chương trình vẫn đưa ra thông báo lỗi. Một ngoại lệ khác phải xảy ra
Câu lệnh
9 cho phép bạn xử lý một ngoại lệ cụ thể. Để bắt một ngoại lệ đã chọn, bạn đặt loại ngoại lệ sau từ khóaCode language: Shell Session [shell]
File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax
6Code language: Shell Session [shell]
Enter the net sales for - Prior period:100 - Current period:120' Traceback [most recent call last]: File "d:/python/try-except.py", line 5, in current = float[input['- Current period:']] ValueError: could not convert string to float: "120'"
7Code language: Python [python]
# get input net sales print['Enter the net sales for'] previous = float[input['- Prior period:']] current = float[input['- Current period:']] # calculate the change in percentage change = [current - previous] * 100 / previous # show the result if change > 0: result = f'Sales increase {abs[change]}%' else: result = f'Sales decrease {abs[change]}%' print[result]
Ví dụ
8Code language: Python [python]
# get input net sales print['Enter the net sales for'] previous = float[input['- Prior period:']] current = float[input['- Current period:']] # calculate the change in percentage change = [current - previous] * 100 / previous # show the result if change > 0: result = f'Sales increase {abs[change]}%' else: result = f'Sales decrease {abs[change]}%' print[result]
Khi bạn chạy một chương trình và nhập một chuỗi cho doanh thu thuần, bạn sẽ nhận được thông báo lỗi tương tự
Tuy nhiên, nếu bạn nhập số không cho doanh thu thuần của giai đoạn trước
0Code language: Shell Session [shell]
File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax
… bạn sẽ nhận được thông báo lỗi sau
1
File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax
Code language: Shell Session [shell]
Lần này bạn có ngoại lệ
98. Phép chia này cho ngoại lệ bằng 0 được gây ra bởi câu lệnh sauCode language: Python [python]
current = 1 if current < 10 current += 1
2Code language: Shell Session [shell]
File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax
Và lý do là giá trị của
99 bằng khôngCode language: Python [python]
current = 1 if current < 10 current += 1
Xử lý nhiều ngoại lệ
9 cho phép bạn xử lý nhiều trường hợp ngoại lệ bằng cách chỉ định nhiều mệnh đềCode language: Shell Session [shell]
File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax
6Code language: Shell Session [shell]
Enter the net sales for - Prior period:100 - Current period:120' Traceback [most recent call last]: File "d:/python/try-except.py", line 5, in current = float[input['- Current period:']] ValueError: could not convert string to float: "120'"
3Code language: Shell Session [shell]
File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax
Điều này cho phép bạn phản hồi từng loại ngoại lệ khác nhau
Nếu bạn muốn có cùng phản hồi đối với một số loại ngoại lệ, bạn có thể nhóm chúng thành một mệnh đề
6Code language: Shell Session [shell]
Enter the net sales for - Prior period:100 - Current period:120' Traceback [most recent call last]: File "d:/python/try-except.py", line 5, in current = float[input['- Current period:']] ValueError: could not convert string to float: "120'"
4Code language: Shell Session [shell]
File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax
Ví dụ sau đây cho thấy cách sử dụng
9 để xử lý các ngoại lệCode language: Shell Session [shell]
File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax
6 vàCode language: Python [python]
# get input net sales print['Enter the net sales for'] previous = float[input['- Prior period:']] current = float[input['- Current period:']] # calculate the change in percentage change = [current - previous] * 100 / previous # show the result if change > 0: result = f'Sales increase {abs[change]}%' else: result = f'Sales decrease {abs[change]}%' print[result]
98Code language: Python [python]
current = 1 if current < 10 current += 1
5Code language: Shell Session [shell]
File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax
Khi bạn nhập số 0 cho doanh thu thuần của giai đoạn trước
6Code language: Shell Session [shell]
File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax
… bạn sẽ gặp lỗi sau
7Code language: Shell Session [shell]
File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax
Đó là một cách tốt để phát hiện các lỗi chung khác bằng cách đặt khối
16 ở cuối danh sáchCode language: Python [python]
# get input net sales print['Enter the net sales for'] previous = float[input['- Prior period:']] current = float[input['- Current period:']] # calculate the change in percentage change = [current - previous] * 100 / previous # show the result if change > 0: result = f'Sales increase {abs[change]}%' else: result = f'Sales decrease {abs[change]}%' print[result]