>>> print(1 + "kushal") Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'str'
处理异常
我们使用 try…except 块来处理任意异常。基本的语法像这样:
1 2 3 4 5 6 7
try: statements to be inside try clause statement2 statement3 ... except ExceptionName: statements to evaluated in case of ExceptionName happens
>>> def get_number(): ... "Returns a float number" ... number = float(input("Enter a float number: ")) ... return number ... >>> >>> while True: ... try: ... print(get_number()) ... except ValueError: ... print("You entered a wrong value.") ... Enter a float number: 45.0 45.0 Enter a float number: 24,0 You entered a wrong value. Enter a float number: Traceback (most recent call last): File "<stdin>", line 3, in <module> File "<stdin>", line 3, in get_number KeyboardInterrupt
>>> raise ValueError("A value error happened.") Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: A value error happened.
我们可以捕获这些异常就像任何其它普通异常一样。
1 2 3 4 5 6
>>> try: ... raise ValueError("A value error happened.") ... except ValueError: ... print("ValueError in our code.") ... ValueError in our code.