- 异常:程序运行时,若是
python解释器
遇到一些错误,而且提示一些错误信息及其说明- 抛出:程序异常而且提示等动做
在程序中捕获异常通常用try
来捕获python
最简单捕获方式code
try: 异常语法 except: 异常输出
编写一个不能处0的案例开发
s1=int(input("请输入一个数字:")) try: result = 9 / s1 except: print("不能为0")
请输入一个数字:0 不能为0 Process finished with exit code 0
在程序中咱们要根据不一样的错误返回不一样的信息get
代码格式以下:input
try: 异常代码 except 异常类型: 提示 except 异常类型: 提示
try: s1 = int(input("请输入一个数字:")) result = 9 / s1 except ZeroDivisionError: print("不能为0") except ValueError: print("请输入正确的整数")
结果1:it
请输入一个数字:a 请输入正确的整数 Process finished with exit code 0
结果2:io
请输入一个数字:0 不能为0 Process finished with exit code0
在程序中会遇到未知错误,又想让程序运行,因此咱们要捕获斌输出class
格式:语法
try: 异常代码 except ZeroDivisionError: 错误提示 except Exception as a: 未知信息
例子:程序
try: s1 = int(input("请输入一个数字:")) result = 9 / s1 except ZeroDivisionError: print("不能为0") except Exception as a: print(f"错误提示{a}")
结果:
请输入一个数字:a 错误提示invalid literal for int() with base 10: 'a' Process finished with exit code 0
实际开发中有些难度,下面为完整的格式
try: 异常代码 except 异常类型: 提示信息 except Exception as a: 提示信息 else: 没有异常代码 finally: 有没有异常都会执行
例子:
try: s1 = int(input("请输入一个数字:")) result = 9 / s1 except ZeroDivisionError: print("不能为0") except Exception as a: print(f"错误提示{a}") else: print("123") finally: print("有没有都会执行")
结果:
请输入一个数字:0 不能为0 有没有都会执行 Process finished with exit code 0
例子:
输入的年龄大于0且小于100
def getAge(): age = int(input("请输入年龄:")) if age>0 & age<100: return age; ex=Exception("age输入错误") return ex; print(getAge())
结果:
请输入年龄:-1 age输入错误 Process finished with exit code 0