Hướng dẫn exception in for loop python - ngoại lệ trong for loop python

Một ngoại lệ xảy ra khi chương trình của tôi không thể tìm thấy phần tử mà nó đang tìm kiếm, tôi muốn đăng nhập sự kiện trong CSV, hiển thị thông báo xảy ra lỗi và tiếp tục. Tôi đã đăng nhập thành công sự kiện trong CSV và hiển thị tin nhắn, sau đó chương trình của tôi nhảy ra khỏi vòng lặp và dừng. Làm thế nào tôi có thể hướng dẫn Python tiếp tục. Vui lòng kiểm tra mã của tôi.

sites = ['TCF00670','TCF00671','TCF00672','TCF00674','TCF00675','TCF00676','TCF00677']`

with open('list4.csv','wb') as f:
    writer = csv.writer(f)
    try:
        for s in sites:
            adrs = "http://turnpikeshoes.com/shop/" + str(s)
            driver = webdriver.PhantomJS()
            driver.get(adrs)
            time.sleep(5)
            LongDsc = driver.find_element_by_class_name("productLongDescription").text
            print "Working.." + str(s)
            writer.writerows([[LongDsc]])
    except:
        writer.writerows(['Error'])
        print ("Error Logged..")
        pass

    driver.quit()
print "Complete."

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

# 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)
1 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:
        print("Oops!", sys.exc_info()[0], "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)
2, 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:
        print("Oops!", sys.exc_info()[0], "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)
3. 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:
        print("Oops!", sys.exc_info()[0], "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)
3 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:
        print("Oops!", sys.exc_info()[0], "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)
3, 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:
        print("Oops!", sys.exc_info()[0], "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)
2 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:
        print("Oops!", sys.exc_info()[0], "occurred.")
        print("Next entry.")
        print()
print("The reciprocal of", entry, "is", r)
1.

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

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

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

# 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)
8. Mã xử lý các ngoại lệ được viết 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.

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

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

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
0 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 ____2020 (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

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
4 bên trong mô -đun
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
5. Chúng ta có thể thấy rằng
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 gây 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
7 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
8 gây 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
9.

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)
0, 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
0.

Đâ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
0 sẽ bắt được.

Một điều khoả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)
8 có thể có bất kỳ số lượng nào của các đ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 để 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)
5.

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

# 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)
8 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
# 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 tùy chọn với câu lệnh
# 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)
8.

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

Nếu chúng ta vượt qua một số lẻ:

Enter a number: 1
Not an even number!

Nếu chúng ta vượt qua một số chẵn, đối ứng được tính toán và hiển thị.

Enter a number: 4
0.25

Tuy nhiên, nếu chúng tôi vượt qua 0, chúng tôi sẽ nhận được

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
9 vì khối mã bên 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)
7 không được xử lý trước
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 trước.

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

Python thử ... cuối cùng

Tuyên bố

# 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)
8 trong Python có thể có mệnh đề
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
3 tùy chọn. Điều khoản này được thực thi bất kể điều gì, và thường được sử dụng để phát hành các tài nguyên bên ngoài.

Ví dụ: chúng tôi có thể được kết nối với một trung tâm dữ liệu từ xa thông qua mạng hoặc làm việc với một tệp hoặc giao diện người dùng đồ họa (GUI).

Trong tất cả các trường hợp này, chúng ta phải dọn dẹp tài nguyên trước khi chương trình tạm dừng cho dù nó có chạy thành công hay không. Các hành động này (đóng một tệp, GUI hoặc ngắt kết nối khỏi mạng) được thực hiện trong mệnh đề

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
3 để đảm bảo thực thi.

Dưới đây là một ví dụ về các hoạt động tập tin để minh họa điều này.

# 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)
0

Loại cấu trúc này đảm bảo rằng tệp được đóng ngay cả khi xảy ra ngoại lệ trong quá trình thực hiện chương trình.

Làm thế nào để bạn xử lý một lỗi vòng lặp?

Đầu ra. Một cách để thực hiện vòng lặp mà không bị phá vỡ là di chuyển mã gây ra ngoại lệ cho một phương thức khác xử lý ngoại lệ. Nếu bạn đã thử bắt trong vòng lặp, nó sẽ được thực hiện hoàn toàn truyền cảm hứng cho các ngoại lệ.move the code that causes the exception to another method that handles the exception. If you have try catch within the loop it gets executed completely inspite of exceptions.

Làm cách nào để thêm một 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 thử. Hoạt động quan trọng có thể tăng một ngoại lệ được đặt bên trong mệnh đề thử. Mã xử lý các ngoại lệ được viết trong mệnh đề ngoại trừ.using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.

Trường hợp ngoại lệ trong Python là gì?

Một ngoại lệ là một sự kiện, xảy ra trong quá trình thực hiện một chương trình phá vỡ luồng thông thường của các hướng dẫn của chương trình.Nói chung, khi một kịch bản Python gặp phải một tình huống mà nó không thể đối phó, nó sẽ đặt ra một ngoại lệ.Một ngoại lệ là một đối tượng Python đại diện cho một lỗi.an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error.

Là thử

Câu lệnh Try-Except là một khối mã cho phép chương trình của bạn thực hiện các hành động thay thế trong trường hợp xảy ra lỗi.Trước tiên, Python sẽ cố gắng thực thi mã trong câu lệnh TRY (Khối mã 1).Nếu không có ngoại lệ xảy ra, câu lệnh ngoại trừ bị bỏ qua và việc thực hiện câu lệnh thử đã kết thúc.. Python will first attempt to execute the code in the try statement (code block 1). If no exception occurs, the except statement is skipped and the execution of the try statement is finished.