异常未得到正确处理

时间:2019-10-13 21:33:09

标签: python exception python-3.7.4

enter image description here

我的异常处理似乎无法正常工作。当我输入一个字符串作为输入时,不会出现正确的异常。当我输入一个负数时,我也会遇到同样的问题。有人知道如何解决这个问题吗?

我试图更改引发异常的条件,但仍然没有找到解决问题的方法。

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()

如果输入的输入为1,则预期输出应为如下所示的块:(请参见上面输出的屏幕截图)

1 个答案:

答案 0 :(得分:1)

您的异常处理有问题。由于您正在尝试将输入本身转换为整数,因此如果无法将输入转换为整数,它将在此处抛出ValueError。而且您没有任何ValueError异常处理,因此它将转到默认异常块。尝试这种方式:

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