Search code examples
pythoncode-readability

Raising errors: Ugly code... Better way to write?


def positive_int(value):
    try:
        ivalue = int(value)
    except:
        raise argparse.ArgumentTypeError("%s is an invalid positive int value" % value)
    if ivalue <= 0:
        raise argparse.ArgumentTypeError("%s is an invalid positive int value" % value)
    return ivalue

Just think that the code above is brutally ugly. The first part is error-inducing and the other is a check if the value is satisfiable. Error should be raised if at least one of them fails. Is there a way to string these to checks together, so that I don't need to repeat lines? Or just a better and prettier alternative in general? Thanks a lot :)


Solution

  • This will raise a generic Exception if the value is negative inside the try: block, causing it to re-raise the same exception as it would if int(value) threw an exception

    def positive_int(value):
        try:
            ivalue = int(value)
            if ivalue <= 0:
                raise Exception
        except:
            raise argparse.ArgumentTypeError("%s is an invalid positive int value" % value)
    
        return ivalue