Hướng dẫn can we use try with except in python? - chúng ta có thể sử dụng thử với ngoại trừ trong python không?


Khối

The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
0 cho phép bạn kiểm tra một khối mã cho lỗi.

Khối

The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
1 cho phép bạn xử lý lỗi.

Khối

The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
2 cho phép bạn thực thi mã khi không có lỗi.

Khối

The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
3 cho phép bạn thực thi mã, bất kể kết quả của các khối cố gắng và ngoại trừ.


Xử lý ngoại lệ

Khi xảy ra lỗi hoặc ngoại lệ như chúng ta gọi, Python thường sẽ dừng và tạo thông báo lỗi.

Các ngoại lệ này có thể được xử lý bằng cách sử dụng câu lệnh

The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

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

Thí dụ

Khối

The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
0 sẽ tạo ra một ngoại lệ, vì
The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
6 không được xác định:

thử: & nbsp; in (x) ngoại trừ: & nbsp; in ("một ngoại lệ đã xảy ra")
  print(x)
except:
  print("An exception occurred")

Hãy tự mình thử »

Vì khối thử làm tăng lỗi, khối ngoại trừ sẽ được thực thi.

Không có khối thử, chương trình sẽ gặp sự cố và gây ra lỗi:

Thí dụ

Khối

The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
0 sẽ tạo ra một ngoại lệ, vì
The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
6 không được xác định:

thử: & nbsp; in (x) ngoại trừ: & nbsp; in ("một ngoại lệ đã xảy ra")

Hãy tự mình thử »


Vì khối thử làm tăng lỗi, khối ngoại trừ sẽ được thực thi.

Không có khối thử, chương trình sẽ gặp sự cố và gây ra lỗi:

Thí dụ

Khối

The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
0 sẽ tạo ra một ngoại lệ, vì
The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
6 không được xác định:

thử: & nbsp; in (x) ngoại trừ: & nbsp; in ("một ngoại lệ đã xảy ra")
  print(x)
except NameError:
  print("Variable x is not defined")
except:
  print("Something else went wrong")

Hãy tự mình thử »



Vì khối thử làm tăng lỗi, khối ngoại trừ sẽ được thực thi.

Không có khối thử, chương trình sẽ gặp sự cố và gây ra lỗi:

Thí dụ

Khối

The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
0 sẽ tạo ra một ngoại lệ, vì
The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
6 không được xác định:

thử: & nbsp; in (x) ngoại trừ: & nbsp; in ("một ngoại lệ đã xảy ra")
  print("Hello")
except:
  print("Something went wrong")
else:
  print("Nothing went wrong")

Hãy tự mình thử »


Vì khối thử làm tăng lỗi, khối ngoại trừ sẽ được thực thi.

Không có khối thử, chương trình sẽ gặp sự cố và gây ra lỗi:

Thí dụ

Khối

The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
0 sẽ tạo ra một ngoại lệ, vì
The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
6 không được xác định:
  print(x)
except:
  print("Something went wrong")
finally:
  print("The 'try except' is finished")

Hãy tự mình thử »

Vì khối thử làm tăng lỗi, khối ngoại trừ sẽ được thực thi.

Thí dụ

Khối

The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
0 sẽ tạo ra một ngoại lệ, vì
The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
6 không được xác định:

thử: & nbsp; in (x) ngoại trừ: & nbsp; in ("một ngoại lệ đã xảy ra")
  f = open("demofile.txt")
  try:
    f.write("Lorum Ipsum")
  except:
    print("Something went wrong when writing to the file")
  finally:
    f.close()
except:
  print("Something went wrong when opening the file")

Hãy tự mình thử »

Vì khối thử làm tăng lỗi, khối ngoại trừ sẽ được thực thi.


Không có khối thử, chương trình sẽ gặp sự cố và gây ra lỗi:

Tuyên bố này sẽ gây ra lỗi, vì

The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
6 không được xác định:

in (x)

Thí dụ

Khối

The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
0 sẽ tạo ra một ngoại lệ, vì
The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
6 không được xác định:

thử: & nbsp; in (x) ngoại trừ: & nbsp; in ("một ngoại lệ đã xảy ra")

Hãy tự mình thử »
  raise Exception("Sorry, no numbers below zero")

Hãy tự mình thử »

Vì khối thử làm tăng lỗi, khối ngoại trừ sẽ được thực thi.

Không có khối thử, chương trình sẽ gặp sự cố và gây ra lỗi:

Thí dụ

Khối

The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
0 sẽ tạo ra một ngoại lệ, vì
The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
6 không được xác định:

thử: & nbsp; in (x) ngoại trừ: & nbsp; in ("một ngoại lệ đã xảy ra")

Hãy tự mình thử »
  raise TypeError("Only integers are allowed")

Hãy tự mình thử »



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ó 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)
4 gọi chức nă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, từ đó gọi chức nă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)
6. Nếu một ngoại lệ xảy ra trong 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)
6 nhưng không được xử lý trong
# 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, ngoại lệ sẽ chuyển sang
# 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 và sau đó đế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 Exception as e:
        print("Oops!", e.__class__, "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)
4.

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!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

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

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!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
0. Mã xử lý các ngoại lệ được viết trong Điều khoản
The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

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

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!  occurred.
Next entry.

The entry is 0
Oops!  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 ____10.

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

The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
1 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!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
1 (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

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
7 bên trong mô -đun
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
8. Chúng ta có thể thấy rằng
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
9 gây ra
>>> 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!
0 và
>>> 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!
1 gây ra
>>> 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!
2.

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

>>> 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!
3, 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!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

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

Đâ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!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

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

Một điều khoản

The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

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

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
1 để 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

# 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)
2.

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!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
0 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
The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
2 tùy chọn với câu lệnh
The entry is a
Oops!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

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

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 ____10.

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!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
1 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!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
1 (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

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
7 bên trong mô -đun
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
8. Chúng ta có thể thấy rằng
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
9 gây ra
>>> 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!
0 và
>>> 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!
1 gây ra
>>> 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!
2.

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

Vì mọi ngoại lệ trong Python thừa hưởng từ lớp cơ sở >>> 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!3, 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!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

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

Đâ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!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
1 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!  occurred.
Next entry.

The entry is 0
Oops!  occured.
Next entry.

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

The entry is 0
Oops!  occured.
Next entry.

The entry is 2
The reciprocal of 2 is 0.5
1 để 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ệ.

Bạn có thể thử bên trong một Python ngoại trừ không?

Chúng ta có thể lồng nhau các khối ngoại trừ thử trong Python. Trong trường hợp này, nếu một ngoại lệ được nâng lên trong khối thử lồng nhau, khối lồng nhau ngoại trừ được sử dụng để xử lý nó. Trong trường hợp lồng nhau ngoại trừ không thể xử lý nó, các khối bên ngoài được sử dụng để xử lý ngoại lệ.. In this case, if an exception is raised in the nested try block, the nested except block is used to handle it. In case the nested except is not able to handle it, the outer except blocks are used to handle the exception.

Thử gì

0. Python thử, ngoại trừ câu lệnh bắt được một ngoại lệ.Nó được sử dụng để kiểm tra mã cho một lỗi được viết trong câu lệnh thử.Nếu gặp phải lỗi, nội dung của khối ngoại trừ có thể chạy.used to test code for an error which is written in the “try” statement. If an error is encountered, the contents of the “except” block are run.

Nên cố gắng luôn luôn có ngoại trừ trong Python?

Nếu không có ngoại lệ, thì chỉ thử mệnh đề sẽ chạy, ngoại trừ mệnh đề sẽ không được thực thi.Nếu bất kỳ ngoại lệ nào xảy ra, mệnh đề thử sẽ bị bỏ qua và ngoại trừ mệnh đề sẽ chạy.Nếu bất kỳ ngoại lệ nào xảy ra, nhưng mệnh đề ngoại trừ trong mã không xử lý nó, nó sẽ được chuyển sang các câu lệnh thử bên ngoài.. If any exception occurs, the try clause will be skipped and except clause will run. If any exception occurs, but the except clause within the code doesn't handle it, it is passed on to the outer try statements.

Bạn có thể có hai thử

Trong Python, các khối Except thử có thể được sử dụng để bắt và trả lời một hoặc nhiều trường hợp ngoại lệ.Trong trường hợp một quy trình tăng nhiều hơn một ngoại lệ có thể, tất cả chúng đều có thể được xử lý bằng một mệnh đề ngoại trừ duy nhất.try-except blocks can be used to catch and respond to one or multiple exceptions. In cases where a process raises more than one possible exception, they can all be handled using a single except clause.