Python thử lại nếu có lỗi

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

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

Code language: Shell Session [shell]
9 của Python để 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 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ố

# 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

Điều gì xảy ra nếu thử không thành công trong Python?

Nếu bất kỳ mã nào trong câu lệnh try gây ra lỗi, việc thực thi mã sẽ dừng lại và chuyển sang câu lệnh ngoại trừ . Tại đây, nó sẽ thực thi mã và nếu vì bất kỳ lý do gì, có lỗi trong câu lệnh ngoại trừ, bạn sẽ nhận được thông báo Trong khi xử lý ngoại lệ trên, một ngoại lệ khác đã xảy ra.

3 loại lỗi trong Python là gì?

Có ba loại lỗi chính có thể phân biệt được trong Python. lỗi cú pháp, ngoại lệ và lỗi logic .

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

Nếu tình huống thỏa mãn các điều kiện trên, bạn không cần phải sử dụng thử. 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.

Chúng ta có thể sử dụng if trong TRY trong Python không?

Làm được .

Chủ Đề