简体   繁体   中英

How to skip execution if an exception occurs in Python

I am trying to do exception handling in the below code. If there is an exception it should skip the next statements in the try block and should directly go to except block and continue the loop.

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

Actual output:

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

Expected output:

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

Hi first of all you can have look at here to understand more in dept how exceptions work in 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM