Home > OS >  How to combine value errors?
How to combine value errors?

Time:02-21

I have two function which check correctness of datas. Both function raise ValueError. Those funcions are executing in "for" loop so when one function will raise error, second will not be executed. Is there any possibility to combine both ValueErrors and return them via third function? Ex:

datas = [4, "is", "data", None]

def func(word):
    if not word:
        raise ValueError("Wrong data!")

def func1(word):
    if type(data) != str:
        raise ValueError("Data isn't string!")

for data in datas:
    func(data)
    func1(data)

What I want as output:

ValueError: Wrong data!
ValueError: Data isn't string!

I'm not sure if it possible with ValueErrors but maybe there is some other way of combine errors?

CodePudding user response:

The least hacky way to achieve this would be to accumulate the exceptions in a list, then handle the errors as you see fit:

datas = [4, "is", "data", None]

errors = []

def func(word):
    if not word:
        raise ValueError("Wrong data!")

def func1(word):
    if type(data) != str:
        raise ValueError("Data isn't string!")

for data in datas:
    try:
        func(data)
        func1(data)
    except ValueError as e:
        errors.append(e)

for error in errors:
     print(error)

will output

Data isn't string!
Wrong data!
  • Related