afg229
afg229

Reputation: 53

Exceptions not being handled correctly

enter image description here

My exception handling does not seem to be working correctly. When I enter a string as input, the correct exception does not come up. When I enter a negative number, I have the same issue. Does anyone know how to fix this?

I tried to change the conditions that raise exceptions, but still did not find a solution to the issue.

def main():
    try:
        height = int(input())
        check_height = type(height)
        if height == 0 or height > 999:
            raise Exception
        elif check_height != int:
            raise TypeError
        elif height < 0:
            raise ValueError
        else:
            for blocks in range(height):
                if blocks == 0:
                    print ("+-+")
                    print ("| |")
                    print ("+-+", end = "")
                else:
                    print ("-+")
                    for num in range(blocks):
                        print("  ", end = "")
                    print ("| |")
                    for num in range(blocks):
                        print("  ", end = "")
                    print ("+-+", end = "")
            print("\n")

    except Exception:
        print("Value can't be equal to 0 or greater than 999")
    except TypeError:
        print("Value is not an integer")
    except ValueError:
        print("Value is less than 0")
    finally:
        pass

main()

The expected output should be a block that looks like this if the input entered was 1: (see screenshot of output above)

Upvotes: 0

Views: 94

Answers (1)

san
san

Reputation: 1515

Your exception handling had issues. Since you are trying to convert the input itself to integer, so it would throw ValueError right there if the input can not be converted to integer. And you did not have any ValueError exception handling, so it was going to the default exception block. Try this way:

try:
    height = int(input())
    # check_height = type(height)
    if height <= 0 or height > 999:
        raise Exception
    # elif check_height != int:
    #     raise TypeError
    # elif height < 0:
    #    raise ValueError
    else:
        for blocks in range(height):
            if blocks == 0:
                print ("+-+")
                print ("| |")
                print ("+-+", end = "")
            else:
                print ("-+")
                for num in range(blocks):
                    print("  ", end = "")
                print ("| |")
                for num in range(blocks):
                    print("  ", end = "")
                print ("+-+", end = "")
        print("\n")
except ValueError:
    print("Value is not an integer")
# except TypeError:
#     print("Value is not an integer")
except Exception:
    print("Value can't be less than 1 or greater than 999")
finally:
    pass

Upvotes: 1

Related Questions