r/pythonhelp • • Mar 31 '22

HOMEWORK Condensing try except block

Is there a way to condense these into one block? They do the same thing and I'm trying to learn how to condense them.

    try:
        try:
            b = int(b2)
        except ValueError as e:
            raise InvalidInput(str(e))
        try:
            g = int(g2)
        except ValueError as e:
            raise InvalidInput(str(e))
        s = (int(g2)) - int(b2) / 2
    except InvalidInput as e:
        return str(e), 400
2 Upvotes

5 comments sorted by

1

u/MT1961 Mar 31 '22

Since you are just effectively rethrowing the exception, why not just put the two conversions (b and g) into the same try except block?

1

u/PracticalTale6528 Mar 31 '22

How do you mean?

1

u/MT1961 Mar 31 '22

try:
b = int(b2)
g = int(g2)
except ValueError as e:
return str(e), 400

Basically, this instead of what you have.

1

u/PracticalTale6528 Mar 31 '22

Well, I need them to verify different errors but it's the same code. Instead of if either of the conditions is true.

i.e: if error for b is true tell user b is bad vice versa with g

2

u/MT1961 Mar 31 '22

You could simply create an error string ..

error_string = "B value is bad"
do the conversion b = int(b2)
error_string = "G value is bad"
g = int(g2)
error_string = "No errors"
except:
return error_string, 400