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

Bài Viết Liên Quan

Chủ Đề