--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-6-893398416ed7> in <module> ----> 1 a = 5 + '10'
TypeError: unsupported operand type(s) for +: 'int'and'str'
抛出异常
如果要在满足特定条件时强制发生异常,则可以使用 raise 关键字。
x = -5 if x < 0: raise Exception('x should not be negative.')
--------------------------------------------------------------------------- Exception Traceback (most recent call last) <ipython-input-4-2a9e7e673803> in <module> 1 x = -5 2if x < 0: ----> 3 raise Exception('x should not be negative.')
x = -5 assert (x >= 0), 'x is not positive.' # --> 如果 x >= 0,代码将正常运行
--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) <ipython-input-7-f9b059c51e45> in <module> 1 x = -5 ----> 2 assert (x >= 0), 'x is not positive.' 3# --> Your code will be fine if x >= 0 AssertionError: x isnot positive.
# 这将捕获所有可能的异常 try: a = 5 / 0 except: print('some error occured.') # 可以捕获异常类型 try: a = 5 / 0 except Exception as e: print(e) # 最好指定要捕获的异常类型 # 因此,你必须知道可能的错误 try: a = 5 / 0 except ZeroDivisionError: print('Only a ZeroDivisionError is handled here') # 你可以在try块中运行多个语句,并捕获不同的可能的异常 try: a = 5 / 1# 注意:这里没有 ZeroDivisionError b = a + '10' except ZeroDivisionError as e: print('A ZeroDivisionError occured:', e) except TypeError as e: print('A TypeError occured:', e)
Some error occured. Division by zero Only a ZeroDivisionError is handled here A TypeError occured: unsupported operand type(s) for +: 'float'and'str'
else 语句
如果没有发生异常,则可以使用else语句运行。
try: a = 5 / 1 except ZeroDivisionError as e: print('A ZeroDivisionError occured:', e) else: print('Everything is ok')
Everything is ok
finally 语句
你可以使用始终运行的 finally 语句,无论是否存在异常。 例如,这可用于进行一些清理操作。
try: a = 5 / 1# 注意:这里没有 ZeroDivisionError b = a + '10' except ZeroDivisionError as e: print('A ZeroDivisionError occured:', e) except TypeError as e: print('A TypeError occured:', e) else: print('Everything is ok') finally: print('Cleaning up some stuff...')
A TypeError occured: unsupported operand type(s) for +: 'float'and'str' Cleaning up some stuff...
deftest_value(a): if a > 1000: raise ValueTooHighError('Value is too high.') if a < 5: raise ValueTooLowError('Value is too low.', a) # 注意,构造器接受两个参数 return a
try: test_value(1) except ValueTooHighError as e: print(e) except ValueTooLowError as e: print(e.message, 'The value is:', e.value)