name = 'x' if name isnotNone# SyntaxError: invalid syntax print(name)
异常 - 语法正确,可以被执行,但在执行过程中遇到错误,抛出异常,并终止程序
1 2 3
# 10 / 0 # ZeroDivisionError: division by zero # order * 2 # NameError: name 'order' is not defined # 1 + [1, 2] # TypeError: unsupported operand type(s) for +: 'int' and 'list'
处理异常
try-except except block 只接受与它相匹配的异常类型并执行
1 2 3 4 5 6
try: s = input('please enter two numbers separated by comma: ') num1 = int(s.split(',')[0].strip()) num2 = int(s.split(',')[1].strip()) except ValueError as err: print('Value Error: {}'.format(err))
在 except block 中加入多种异常的类型
1 2 3 4 5 6
try: s = input('please enter two numbers separated by comma: ') num1 = int(s.split(',')[0].strip()) num2 = int(s.split(',')[1].strip()) except (ValueError, IndexError) as err: print('Error: {}'.format(err))
1 2 3 4 5 6 7 8
try: s = input('please enter two numbers separated by comma: ') num1 = int(s.split(',')[0].strip()) num2 = int(s.split(',')[1].strip()) except ValueError as err: print('Value Error: {}'.format(err)) except IndexError as err: print('Index Error: {}'.format(err))