簡體   English   中英

Python發生異常時如何跳過執行

[英]How to skip execution if an exception occurs in Python

我正在嘗試在下面的代碼中進行異常處理。 如果有異常,它應該跳過 try 塊中的下一個語句,並應該直接轉到 except 塊並繼續循環。

from functools import reduce

def sumnumbers(list_elements):
    try:
        sum = reduce(lambda x, y: x + y, list_elements)
        return sum
    except Exception as e:
        print("Error in function", list_elements)

a = [[1,2],[3,"hi"],[5,6],[7,8],[9,"hello"]]
for i in a:
    try:
        s = sumnumbers(i)
        print("hello ", i)
    except Exception as e:
        print(e)
        pass

實際輸出:

hello  [1, 2]
Error in function [3, 'hi']
hello  [3, 'hi']
hello  [5, 6]
hello  [7, 8]
Error in function [9, 'hello']
hello  [9, 'hello']

預期輸出:

hello  [1, 2]
Error in function [3, 'hi']
hello  [5, 6]
hello  [7, 8]
Error in function [9, 'hello']

嗨,首先,您可以查看此處以更深入地了解異常在 python 中的工作原理。

from functools import reduce

def sumnumbers(list_elements):
    try:
        sum = reduce(lambda x, y: x + y, list_elements)
        return sum
    except Exception as e:
        raise Exception("Error in function", list_elements)

a = [[1,2],[3,"hi"],[5,6],[7,8],[9,"hello"]]
for i in a:
    try:
        s = sumnumbers(i)
        print("hello ", i)
    except Exception as e:
        print(e)
        pass

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM