错误
- 不符合语法规范,如 invalid syntax
异常
- 定义:语法正确,但在执行过程中遇到错误,如
- ZeroDivisionError:除数为0
- NameError:未定义的变量名
- TypeError:类型错误
- KeyError:字典中的键找不到
- FileNotFindError:发送了读取请求但文件不存在
- 处理
- 内置异常
1 try: 2 s = input('please enter two numbers separated by comma: ') 3 num1 = int(s.split(',')[0].strip()) 4 num2 = int(s.split(',')[1].strip()) 5 6 except (ValueError, IndexError) as err: 7 print('Error:{}'.format(err)) 8 9 print('continue')
-
- 自定义异常
1 class MyInputError(Exception): 2 def __init__(self, value): 3 self.value = value 4 def __str__(self): 5 return("{} is invalie input".format(repr(self.value))) 6 try: 7 raise MyInputError(1) 8 except MyInputError as err: 9 print('Error:{}'.format(err))
- 何时使用异常
- 不确定某段代码能否成功执行,如数据库连接、读取