Bởi Eric Carb
Luồng kiểm soát ngoại lệ - Thử, Ngoại trừ, Khác, Cuối cùng
Ngoại lệ trong Python là đối tượng đại diện cho lỗi. Các ngoại lệ có thể được đưa ra theo nhiều cách, chẳng hạn như chuyển các đối số không hợp lệ cho các hàm [“Boo” + 7], thực hiện một số thao tác bất hợp pháp [12/0] hoặc thậm chí rõ ràng [tăng TypeError]. Theo mặc định, các ngoại lệ dừng các chương trình Python và in Traceback ra bàn điều khiển với thông tin về ngoại lệ và cách nó được tạo ra. Tuy nhiên, câu lệnh try tồn tại để cung cấp luồng điều khiển cho các ngoại lệ để bạn có thể ngăn chương trình của mình bị lỗi và thậm chí sử dụng các đối tượng ngoại lệ để có lợi cho bạn. Điều này thường được gọi là "bắt" một ngoại lệ. Câu lệnh thử trông như thế này
thử
Mã có ngoại lệ mà bạn muốn bắt. Nếu một ngoại lệ được đưa ra, luồng điều khiển sẽ rời khỏi khối này ngay lập tức và đi đến khối ngoại trừ
ngoại trừ [[Ngoại lệ [, Ngoại lệ]]] [dưới dạng VAR]
Mã này chỉ được thực thi nếu một ngoại lệ được đưa ra trong khối thử. Mã được thực thi trong khối này giống như mã bình thường. nếu có ngoại lệ, nó sẽ không tự động bị bắt [và có thể dừng chương trình]
Bạn có thể tùy chọn đặt tên cho các loại ngoại lệ cụ thể trong các câu lệnh except, trong trường hợp đó, khối sẽ chỉ được thực thi nếu một trong các ngoại lệ được đặt tên là ngoại lệ được đưa ra trong lần thử. Khi đặt tên cho nhiều ngoại lệ, hãy sử dụng một tuple. Việc có nhiều câu lệnh ngoại trừ là hợp pháp, mỗi câu lệnh đặt tên cho các loại ngoại lệ khác nhau. Nếu không có ngoại lệ nào được đặt tên trong câu lệnh ngoại trừ, nó sẽ bắt tất cả các ngoại lệ;
Bao gồm biểu thức as với câu lệnh except cho phép bạn lưu trữ đối tượng ngoại lệ được nêu trong khối try trong một biến và sử dụng nó trong khối này. Để lưu trữ một ngoại lệ trong một biến khi không có tên nào được đặt tên, thay vào đó hãy đặt tên là “Ngoại lệ” [i. e. ngoại trừ Ngoại lệ như e]. Chỉ có một biến có thể được liệt kê sau khi
Khối này là bắt buộc [ngay cả khi tất cả những gì nó có là vượt qua]
[khác. ]
Mã này chỉ được thực thi nếu không có ngoại lệ nào được đưa ra trong khối thử. Mã được thực thi trong khối này giống như mã bình thường. nếu có ngoại lệ, nó sẽ không tự động bị bắt [và có thể dừng chương trình]. Lưu ý rằng nếu khối lệnh else được thực thi thì khối lệnh ngoại trừ không được thực thi và ngược lại. Khối này là tùy chọn
[cuối cùng. ]
Mã này luôn thực thi sau các khối khác, ngay cả khi có một ngoại lệ chưa được phát hiện [rõ ràng là không gây ra sự cố] hoặc một câu lệnh trả về ở một trong các khối khác. Mã được thực thi trong khối này giống như mã bình thường. nếu có ngoại lệ, nó sẽ không tự động bị bắt [và có thể dừng chương trình]. Khối này cũng là tùy chọn
Bản tóm tắt. trong hướng dẫn này, bạn sẽ học cách sử dụng câu lệnh Python
9 để 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 người dùng xấu
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
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]
- 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ệnhEnter 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
0
File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax
Code language: Shell Session [shell]
… bạn sẽ nhận được thông báo lỗi sau
1Code language: Shell Session [shell]
File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax
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]