Search code examples
pythonerror-handlingpython-3.5valueerror

Catch ValueError in multiple parts of program


I am trying to raise a ValueError when a variable becomes negative. My problem is that this variable changes values in a few parts of my program. How could I achieve the same result as below with only one raise statement?

import random

a = 5

while True:

    a -= random.randint(0,10)
    if a < 0:
        raise ValueError('Cannot be negative')

    a += random.randint(0,10)
    if a < 0:
        raise ValueError('Cannot be negative')

    a -= random.randint(0,10)
    if a < 0:
        raise ValueError('Cannot be negative')

    a += random.randint(0,10)
    if a < 0:
        raise ValueError('Cannot be negative')

Thank you


Solution

  • I'd suggest using a getter/setter for your variable, and check in the setter. This is exactly the sort of reason they exist