1 try: 2 age = input('请输入年龄') 3 int(age) 4 num2 = input('请输入') 5 int(num2) 6 l = list() 7 l[100] 8 except KeyError as e: 9 print(e) 10 except ValueError as e: # 多分支 11 print('======>', e) 12 except IndexError as e: 13 print(e) 14 except Exception as e: # 万能异常处理 15 print(e) 16 输出: 17 请输入年龄45 18 请输入54 19 list index out of range
可以使用万能异常处理接受一切异常,保证程序的正常运行。
Exception
1 try: 2 age = input('请输入年龄') 3 int(age) 4 num2 = input('请输入') 5 int(num2) 6 l = list() 7 l[100] 8 except KeyError as e: 9 print(e) 10 except ValueError as e: # 多分支 11 print('======>', e) 12 except IndexError as e: 13 print(e) 14 except Exception as e: # 万能异常处理 15 print(e) 16 else: 17 print('如果代码没有异常则执行此处的代码') 18 finally: #虽然如此,无论如何这里的代码都会执行,但是如果异常没有被处理,最终还是会崩溃 19 print('无论代码是否有异常都执行此处的代码') 20 主动触发异常 21 try: 22 raise TypeError('类型错误') 23 except Exception as e: 24 print(e) 25 输出:
自定义异常信息:
1 class Chexception(BaseException): 2 def __init__(self, msg): 3 self.msg = msg 4 5 def __str__(self): # 重写打印信息 6 return '我自己自定义的异常信息' 7 输出: 8 Traceback (most recent call last): 9 File "C:/Users/Administrator/Desktop/python/3月17日/test.py", line 33, in <module> 10 raise Chexception('自定义的异常') 11 __main__.Chexception: 我自己自定义的异常信息
断言 可以判断一个值是否是你期望的值,函数是否继续执行下去:
1 def test(): 2 return 1 3 res = test() 4 assert res ==1 5 print('ooooo') 6 输出: 7 这是断言函数