Hướng dẫn how do you handle an exception in python? - làm thế nào để bạn xử lý một ngoại lệ trong python?

Ngoại lệ trong Python

Python có nhiều trường hợp ngoại lệ tích hợp được nêu ra khi chương trình của bạn gặp lỗi (một cái gì đó trong chương trình bị sai).

Khi các trường hợp ngoại lệ này xảy ra, trình thông dịch Python dừng quy trình hiện tại và chuyển nó đến quá trình gọi cho đến khi nó được xử lý. Nếu không được xử lý, chương trình sẽ bị sập.

Ví dụ: chúng ta hãy xem xét một chương trình trong đó chúng ta có chức năng

The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
0 gọi chức năng
The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
1, từ đó gọi chức năng
The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
2. Nếu một ngoại lệ xảy ra trong hàm
The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
2 nhưng không được xử lý trong
The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
2, ngoại lệ sẽ chuyển sang
The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
1 và sau đó đến
The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
0.

Nếu không bao giờ được xử lý, một thông báo lỗi được hiển thị và chương trình của chúng tôi dừng lại bất ngờ.


Bắt các trường hợp ngoại lệ trong Python

Trong Python, các trường hợp ngoại lệ có thể được xử lý bằng cách sử dụng câu lệnh

The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
7.

Hoạt động quan trọng có thể tăng một ngoại lệ được đặt bên trong mệnh đề

The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
7. Mã xử lý các ngoại lệ được viết trong mệnh đề
The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
9.

Do đó, chúng tôi có thể chọn những hoạt động để thực hiện một khi chúng tôi đã bắt được ngoại lệ. Đây là một ví dụ đơn giản.

# import module sys to get the type of exception
import sys

randomList = ['a', 0, 2]

for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except:
        print("Oops!", sys.exc_info()[0], "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)

Đầu ra

The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5

Trong chương trình này, chúng tôi lặp qua các giá trị của danh sách danh sách ngẫu nhiên. Như đã đề cập trước đây, phần có thể gây ra một ngoại lệ được đặt bên trong khối

The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
7.

Nếu không xảy ra ngoại lệ, khối

The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
9 bị bỏ qua và dòng chảy bình thường tiếp tục (cho giá trị cuối cùng). Nhưng nếu có bất kỳ ngoại lệ nào xảy ra, nó bị bắt bởi khối
The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
9 (giá trị thứ nhất và thứ hai).

Ở đây, chúng tôi in tên của ngoại lệ bằng hàm

# import module sys to get the type of exception
import sys

randomList = ['a', 0, 2]

for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except Exception as e:
        print("Oops!", e.__class__, "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)
3 bên trong mô -đun
# import module sys to get the type of exception
import sys

randomList = ['a', 0, 2]

for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except Exception as e:
        print("Oops!", e.__class__, "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)
4. Chúng ta có thể thấy rằng
# import module sys to get the type of exception
import sys

randomList = ['a', 0, 2]

for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except Exception as e:
        print("Oops!", e.__class__, "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)
5 gây ra
# import module sys to get the type of exception
import sys

randomList = ['a', 0, 2]

for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except Exception as e:
        print("Oops!", e.__class__, "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)
6 và
# import module sys to get the type of exception
import sys

randomList = ['a', 0, 2]

for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except Exception as e:
        print("Oops!", e.__class__, "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)
7 gây ra
# import module sys to get the type of exception
import sys

randomList = ['a', 0, 2]

for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except Exception as e:
        print("Oops!", e.__class__, "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)
8.

Vì mọi ngoại lệ trong Python thừa hưởng từ lớp cơ sở

# import module sys to get the type of exception
import sys

randomList = ['a', 0, 2]

for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except Exception as e:
        print("Oops!", e.__class__, "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)
9, chúng tôi cũng có thể thực hiện nhiệm vụ trên theo cách sau:

# import module sys to get the type of exception
import sys

randomList = ['a', 0, 2]

for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except Exception as e:
        print("Oops!", e.__class__, "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)

Chương trình này có cùng đầu ra với chương trình trên.


Bắt các trường hợp ngoại lệ cụ thể trong Python

Trong ví dụ trên, chúng tôi đã không đề cập đến bất kỳ ngoại lệ cụ thể nào trong mệnh đề

The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
9.

Đây không phải là một thực hành lập trình tốt vì nó sẽ bắt được tất cả các trường hợp ngoại lệ và xử lý mọi trường hợp theo cùng một cách. Chúng tôi có thể chỉ định ngoại lệ nào một mệnh đề

The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
9 sẽ bắt được.

Một điều khoản

The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
7 có thể có bất kỳ số lượng nào của các mệnh đề
The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
9 để xử lý các trường hợp ngoại lệ khác nhau, tuy nhiên, chỉ có một điều sẽ được thực thi trong trường hợp xảy ra ngoại lệ.

Chúng ta có thể sử dụng một bộ giá trị để chỉ định nhiều ngoại lệ trong một mệnh đề ngoại trừ. Dưới đây là một ví dụ mã giả.

try:
   # do something
   pass

except ValueError:
   # handle ValueError exception
   pass

except (TypeError, ZeroDivisionError):
   # handle multiple exceptions
   # TypeError and ZeroDivisionError
   pass

except:
   # handle all other exceptions
   pass

Tăng ngoại lệ trong Python

Trong chương trình Python, các trường hợp ngoại lệ được nêu ra khi lỗi xảy ra khi chạy. Chúng tôi cũng có thể nâng cao các ngoại lệ bằng cách sử dụng từ khóa

try:
   # do something
   pass

except ValueError:
   # handle ValueError exception
   pass

except (TypeError, ZeroDivisionError):
   # handle multiple exceptions
   # TypeError and ZeroDivisionError
   pass

except:
   # handle all other exceptions
   pass
4.

Chúng ta có thể tùy chọn chuyển các giá trị đến ngoại lệ để làm rõ lý do tại sao ngoại lệ đó được nâng lên.

>>> raise KeyboardInterrupt
Traceback (most recent call last):
...
KeyboardInterrupt

>>> raise MemoryError("This is an argument")
Traceback (most recent call last):
...
MemoryError: This is an argument

>>> try:
...     a = int(input("Enter a positive integer: "))
...     if a <= 0:
...         raise ValueError("That is not a positive number!")
... except ValueError as ve:
...     print(ve)
...    
Enter a positive integer: -2
That is not a positive number!

Python thử với mệnh đề khác

Trong một số tình huống, bạn có thể muốn chạy một khối mã nhất định nếu khối mã bên trong

The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
7 chạy mà không có bất kỳ lỗi nào. Đối với những trường hợp này, bạn có thể sử dụng từ khóa
try:
   # do something
   pass

except ValueError:
   # handle ValueError exception
   pass

except (TypeError, ZeroDivisionError):
   # handle multiple exceptions
   # TypeError and ZeroDivisionError
   pass

except:
   # handle all other exceptions
   pass
6 tùy chọn với câu lệnh
The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
7.

Lưu ý: Các trường hợp ngoại lệ trong mệnh đề khác không được xử lý bởi các điều khoản trước ngoại trừ các điều khoản.: Exceptions in the else clause are not handled by the preceding except clauses.

Hãy xem xét một ví dụ:

# program to print the reciprocal of even numbers

try:
    num = int(input("Enter a number: "))
    assert num % 2 == 0
except:
    print("Not an even number!")
else:
    reciprocal = 1/num
    print(reciprocal)

Đầu ra

Trong chương trình này, chúng tôi lặp qua các giá trị của danh sách danh sách ngẫu nhiên. Như đã đề cập trước đây, phần có thể gây ra một ngoại lệ được đặt bên trong khối

The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
7.

Enter a number: 1
Not an even number!

Nếu không xảy ra ngoại lệ, khối

The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
9 bị bỏ qua và dòng chảy bình thường tiếp tục (cho giá trị cuối cùng). Nhưng nếu có bất kỳ ngoại lệ nào xảy ra, nó bị bắt bởi khối
The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
9 (giá trị thứ nhất và thứ hai).

Enter a number: 4
0.25

Ở đây, chúng tôi in tên của ngoại lệ bằng hàm

# import module sys to get the type of exception
import sys

randomList = ['a', 0, 2]

for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except Exception as e:
        print("Oops!", e.__class__, "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)
3 bên trong mô -đun
# import module sys to get the type of exception
import sys

randomList = ['a', 0, 2]

for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except Exception as e:
        print("Oops!", e.__class__, "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)
4. Chúng ta có thể thấy rằng
# import module sys to get the type of exception
import sys

randomList = ['a', 0, 2]

for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except Exception as e:
        print("Oops!", e.__class__, "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)
5 gây ra
# import module sys to get the type of exception
import sys

randomList = ['a', 0, 2]

for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except Exception as e:
        print("Oops!", e.__class__, "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)
6 và
# import module sys to get the type of exception
import sys

randomList = ['a', 0, 2]

for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except Exception as e:
        print("Oops!", e.__class__, "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)
7 gây ra
# import module sys to get the type of exception
import sys

randomList = ['a', 0, 2]

for entry in randomList:
    try:
        print("The entry is", entry)
        r = 1/int(entry)
        break
    except Exception as e:
        print("Oops!", e.__class__, "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)
8.

Enter a number: 0
Traceback (most recent call last):
  File "<string>", line 7, in <module>
    reciprocal = 1/num
ZeroDivisionError: division by zero

Vì mọi ngoại lệ trong Python thừa hưởng từ lớp cơ sở # import module sys to get the type of exception import sys randomList = ['a', 0, 2] for entry in randomList: try: print("The entry is", entry) r = 1/int(entry) break except Exception as e: print("Oops!", e.__class__, "occurred.") print("Next entry.") print() print("The reciprocal of", entry, "is", r)9, chúng tôi cũng có thể thực hiện nhiệm vụ trên theo cách sau:

Chương trình này có cùng đầu ra với chương trình trên.

Bắt các trường hợp ngoại lệ cụ thể trong Python

Trong ví dụ trên, chúng tôi đã không đề cập đến bất kỳ ngoại lệ cụ thể nào trong mệnh đề

The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
9.

Đây không phải là một thực hành lập trình tốt vì nó sẽ bắt được tất cả các trường hợp ngoại lệ và xử lý mọi trường hợp theo cùng một cách. Chúng tôi có thể chỉ định ngoại lệ nào một mệnh đề

The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
9 sẽ bắt được.

try:
   f = open("test.txt",encoding = 'utf-8')
   # perform file operations
finally:
   f.close()

Một điều khoản

The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
7 có thể có bất kỳ số lượng nào của các mệnh đề
The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
9 để xử lý các trường hợp ngoại lệ khác nhau, tuy nhiên, chỉ có một điều sẽ được thực thi trong trường hợp xảy ra ngoại lệ.

Làm thế nào để bạn xử lý một ngoại lệ?

Try-Catch là phương pháp xử lý các ngoại lệ đơn giản nhất. Đặt mã bạn muốn chạy trong khối thử và bất kỳ ngoại lệ Java nào mà mã ném được bắt bởi một hoặc nhiều khối bắt. Phương pháp này sẽ bắt bất kỳ loại ngoại lệ Java nào bị ném. Đây là cơ chế đơn giản nhất để xử lý các ngoại lệ.. Put the code you want to run in the try block, and any Java exceptions that the code throws are caught by one or more catch blocks. This method will catch any type of Java exceptions that get thrown. This is the simplest mechanism for handling exceptions.

Xử lý ngoại lệ trong Python giải thích với ví dụ là gì?

Một ngoại lệ trong Python là một sự cố xảy ra trong khi thực hiện một chương trình khiến cho quá trình thường xuyên của các lệnh của chương trình bị phá vỡ.Khi mã Python xuất hiện trong một điều kiện mà nó không thể xử lý, nó sẽ tăng một ngoại lệ.Một đối tượng trong Python mô tả một lỗi được gọi là ngoại lệ.an incident that happens while executing a program that causes the regular course of the program's commands to be disrupted. When a Python code comes across a condition it can't handle, it raises an exception. An object in Python that describes an error is called an exception.

Các loại ngoại lệ là gì và bạn sẽ xử lý nó như thế nào trong Python?

Thí dụ.Khi một ngoại lệ được ném vào khối thử, việc thực hiện ngay lập tức chuyển sang khối cuối cùng.Sau khi tất cả các câu lệnh trong khối cuối cùng được thực thi, ngoại lệ sẽ được nêu lại và được xử lý trong các câu lệnh ngoại trừ nếu có trong lớp cao hơn tiếp theo của câu lệnh Try-Except.