Làm thế nào để bạn sử dụng ngoại trừ trong python?

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

File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax

Code language: Shell Session [shell]
9 để xử lý ngoại lệ một cách khéo léo

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ụ

current = 1 if current < 10 current += 1

Code language: Python [python]

Nếu bạn cố chạy mã này, bạn sẽ gặp lỗi sau

File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax

Code language: Shell Session [shell]

Trong ví dụ này, trình thông dịch Python đã phát hiện lỗi tại câu lệnh

# 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: Python [python]
0 do dấu hai chấm [

# 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: Python [python]
1] bị thiếu sau câu lệnh

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ố

# 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: Python [python]

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

# 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: Python [python]
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ả sau

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'"

Code language: Shell Session [shell]

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 [

    # 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: Python [python]
    3] đã gây ra ngoại lệ
  • Dòng mã chính xác gây ra ngoại lệ [

    # 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: Python [python]
    4]
  • Tuyên bố gây ra ngoại lệ

    # 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: Python [python]
    5
  • Loại ngoại lệ

    # 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: Python [python]
    6
  • Thông báo lỗi.

    # 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: Python [python]
    7

Bởi vì

# 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: Python [python]
8 không thể chuyển đổi chuỗi

# 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: Python [python]
2 thành một số, trình thông dịch Python đã đưa ra một ngoại lệ

# 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: Python [python]
6

Trong Python, các ngoại lệ có nhiều loại khác nhau như

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'"

Code language: Shell Session [shell]
1,

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'"

Code language: Shell Session [shell]
2, v.v.

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

File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax

Code language: Shell Session [shell]
9

current = 1 if current < 10 current += 1

Code language: Python [python]
9

Câu lệnh

File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax

Code language: Shell Session [shell]
9 hoạt động như sau

  • Các câu lệnh trong mệnh đề

    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'"

    Code language: Shell Session [shell]
    5 thực hiện trước
  • Nếu không có ngoại lệ nào xảy ra, mệnh đề

    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'"

    Code language: Shell Session [shell]
    6 sẽ bị bỏ qua và việc thực thi câu lệnh

    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'"

    Code language: Shell Session [shell]
    5 đã hoàn thành
  • Nếu một ngoại lệ xảy ra tại bất kỳ câu lệnh nào trong mệnh đề

    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'"

    Code language: Shell Session [shell]
    5, phần còn lại của mệnh đề sẽ bị bỏ qua và mệnh đề

    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'"

    Code language: Shell Session [shell]
    6 được thực thi

Lưu đồ sau đây minh họa câu lệnh

File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax

Code language: Shell Session [shell]
9

Vì vậy, để xử lý các ngoại lệ bằng cách sử dụng câu lệnh

File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax

Code language: Shell Session [shell]
9, bạn đặt mã có thể gây ra ngoại lệ trong mệnh đề

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'"

Code language: Shell Session [shell]
5 và mã xử lý ngoại lệ trong mệnh đề

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'"

Code language: Shell Session [shell]
6

Đây là cách bạn có thể viết lại chương trình và sử dụng câu lệnh

File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax

Code language: Shell Session [shell]
9 để xử lý ngoại lệ

# 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: Python [python]
1

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

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'"

Code language: Shell Session [shell]
6

# 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: Python [python]
3

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

# 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: Python [python]
4

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

File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax

Code language: Shell Session [shell]
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óa

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'"

Code language: Shell Session [shell]
6

# 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: Python [python]
7

Ví dụ

# 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: Python [python]
8

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

File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax

Code language: Shell Session [shell]
0

… bạn sẽ nhận được thông báo lỗi sau

File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax

Code language: Shell Session [shell]
1

Lần này bạn có ngoại lệ

current = 1 if current < 10 current += 1

Code language: Python [python]
98. Phép chia này cho ngoại lệ bằng 0 được gây ra bởi câu lệnh sau

File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax

Code language: Shell Session [shell]
2

Và lý do là giá trị của

current = 1 if current < 10 current += 1

Code language: Python [python]
99 bằng không

Xử lý nhiều ngoại lệ

File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax

Code language: Shell Session [shell]
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 đề

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'"

Code language: Shell Session [shell]
6

File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax

Code language: Shell Session [shell]
3

Đ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 đề

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'"

Code language: Shell Session [shell]
6

File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax

Code language: Shell Session [shell]
4

Ví dụ sau đây cho thấy cách sử dụng

File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax

Code language: Shell Session [shell]
9 để xử lý các ngoại lệ

# 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: Python [python]
6 và

current = 1 if current < 10 current += 1

Code language: Python [python]
98

File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax

Code language: Shell Session [shell]
5

Khi bạn nhập số 0 cho doanh thu thuần của giai đoạn trước

File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax

Code language: Shell Session [shell]
6

… bạn sẽ gặp lỗi sau

File "d:/python/try-except.py", line 2 if current < 10 ^ SyntaxError: invalid syntax

Code language: Shell Session [shell]
7

Đó 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

# 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: Python [python]
16 ở cuối danh sách

Tôi có thể sử dụng cái gì thay vì ngoại trừ trong Python?

ngoại trừ. để xử lý các ngoại lệ. Thay vào đó, thư viện contextlib tích hợp sẵn của Python cung cấp một hàm gọi là suppress để xử lý việc này một cách tinh tế hơn.

Tôi có nên sử dụng thử ngoại trừ trong Python không?

Lý do sử dụng try/ngoại trừ là khi bạn có một khối mã để thực thi, khối mã này đôi khi sẽ chạy chính xác và đôi khi không , tùy thuộc vào .

Chủ Đề