Python中for循环出现异常时如何跳过并继续处理?

for 循环中出现不可预测异常时,跳过本次循环并 print 出错误内容,继续执行下一次循环应该如何写?
现在使用的是 try…except…这样的,使用 continue 方法.
但是在实测中,如果连接失败,程序之间停止.
在代码中可以看出,是使用的 bs 抓取 url.程序循环到其中某一条连接时,内容里没有包含指定 a 标签的内容的话,也会报错并终止程序.
应该如何实现继续循环?
for u in product_page_url:
a = requests.get(u.strip())
soup = BeautifulSoup(a.text, ‘html.parser’)
try:
clean_downurl = soup.find(class_ = ‘downurl’).a[‘href’]
b.append(clean_downurl)
print u
except:
continue
Python中for循环出现异常时如何跳过并继续处理?


10 回复

可能 requests.get 这一步就异常了.


# 处理for循环异常并继续执行的几种方法

# 1. 基础try-except包裹整个循环(不推荐)
# 这样遇到第一个异常就会跳出循环
try:
    for item in items:
        process(item)
except Exception:
    pass

# 2. 在循环内部使用try-except(推荐)
items = [1, 2, 'three', 4, 'five', 6]
results = []

for item in items:
    try:
        # 尝试执行可能出错的操作
        result = item * 2
        results.append(result)
        print(f"成功处理: {item} -> {result}")
    except (TypeError, ValueError) as e:
        # 捕获特定异常并继续
        print(f"跳过 {item}: {e}")
        continue  # 继续下一个迭代
    except Exception as e:
        # 捕获其他异常
        print(f"未知错误处理 {item}: {e}")
        continue

print(f"最终结果: {results}")

# 3. 使用函数封装处理逻辑
def safe_process(item):
    try:
        return item * 2
    except TypeError:
        return None

for item in items:
    result = safe_process(item)
    if result is not None:
        results.append(result)

# 4. 使用上下文管理器(更优雅)
from contextlib import suppress

for item in items:
    with suppress(TypeError, ValueError):
        # 这里发生的指定异常会被静默处理
        result = item * 2
        results.append(result)

# 5. 记录异常信息继续执行
import logging

logging.basicConfig(level=logging.INFO)
error_log = []

for index, item in enumerate(items):
    try:
        result = item * 2
        results.append(result)
    except Exception as e:
        error_log.append((index, item, str(e)))
        logging.warning(f"第{index}个元素{item}处理失败: {e}")

# 处理完成后可以查看错误日志
if error_log:
    print(f"共{len(error_log)}个错误: {error_log}")

# 实际示例:处理文件读取
files = ['data1.txt', 'data2.txt', 'missing.txt', 'data3.txt']
all_data = []

for filename in files:
    try:
        with open(filename, 'r') as f:
            content = f.read()
            all_data.append(content)
            print(f"成功读取: {filename}")
    except FileNotFoundError:
        print(f"文件不存在: {filename}")
        continue  # 继续处理下一个文件
    except IOError as e:
        print(f"读取错误 {filename}: {e}")
        continue
    except Exception as e:
        print(f"未知错误 {filename}: {e}")
        continue

print(f"成功读取 {len(all_data)} 个文件")

核心要点:

  • 在循环内部使用try-except,而不是包裹整个循环
  • 尽量捕获具体异常类型,不要只用except Exception
  • 使用continue明确跳过后面的代码
  • 考虑记录错误信息以便后续分析

建议:循环内try-except配合continue是最直接的做法。

在执行 clean_downurl = soup.find(class_ = ‘downurl’).a[‘href’] 的时候。提示 soup 的错误,没有找到 a 标签。然后就终止程序了。这应该怎么写呀?

第一个,你在 requests.get 之前并没有做 try ,所以在连接出错时会报错停止。
第二个,我不知道你这个 BS 的 find 的语法对不对,但是我认为如果 try 不起作用,你可以换个方法,比如在后边做个判断,用 if 代替 try 。

except 没有捉到异常? 加个 Exception 试试?

第一个已经修改 try 的位置,已经解决了,第二个 BS 的语法经过测试是可以正常获取到值的。如果解决不了的话在考虑使用 if 吧。

错误原因是啥,报错信息你能不能看懂

#4 别瞎猜啊, try except 捕获所有异常, try except Exception 捕获 Exception 类型的异常。另外要避免 try except 不加异常类型的用法,这很容易吃掉不应该忽略的异常。

错误原因看得懂的,列表中的某些 url 不存在我找的指定连接,然后就 bs 就提示错误了, requests 的错误是因为网络有时不稳定,连接不到 url 然后报错的。

clean_downurl = soup.find(class_ = ‘downurl’)
if clean_downurl is not None:
clean_downurl = clean_downurl.a[‘href’]
我是习惯这样,如果变量获取了某个值,进行下一步操作前,先判断一下是否为空,是否和预期一致

回到顶部