1. try and except的使用
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13try: # 不能确定正确之行的代码 num = int(input('请输入一个数字:')) print(num) except: # try里面的代码如果有异常/错误 才会之行以下代码 print('请输入正确的整数!!!!') print('*' * 50)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
2. try ,except,else 和finally
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19try: num = int(input('Num:')) result = 8 / num print(result) except ZeroDivisionError: print('0不能做除数') except Exception as r: print('未知错误!!') # 程序没有碰到致命错误 就执行else else: print('hello') finally: # 无论是否遇到异常都会执行 print('!!!!')
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
3. 函数的错误
函数的错误:一级一级向上去找 最终会将异常传递到主函数里面去
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14# 错误发生在demo1中 def demo1(): try: return int(input('请输入正确的整数:')) except Exception as r: print('未知错误 %s' %r) def demo2(): return demo1() print(demo2())
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
4. 抛出异常
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22def input_passwd(): # 1.提示用户输入密码 pwd = input('请输入密码:') # 2.判断密码长度 if len(pwd) >= 8: return pwd # 3.如果<8 就主动抛出异常 print('主动抛出异常') # a.创建异常对象 ex = Exception('密码长度不够,必须大于8位') # b.主动抛出异常 raise ex # 注意:只抛出不捕获 代码会报错 try: print(input_passwd()) except Exception as re: print(re)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
练习
用户可以一直输入数字, 当按ctrl+c之后计算所有数的和;
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13result = 0 while True: try: num = int(input('Num:')) result += num except KeyboardInterrupt: print('运行结果:',result) break
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
最后
以上就是细腻斑马最近收集整理的关于python异常添加的全部内容,更多相关python异常添加内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复