异常
异常的定义
异常的写法
try:可能发生错误的代码except:如果出现异常执行的代码
# 示例:----尝试以r的方式打开文件,如果文件不存在,则以w方式打开try:fo = open("demo.txt", "r")except:fo = open("demo.txt", "w")
捕获异常
- 如果尝试执行的代码的异常类型与要捕获的异常类型不一致,则无法捕获异常;
- 一般
**try**下方只放一行**尝试执行**的代码。try:可能发生错误的代码except 异常类型:如果捕获到该异常类型执行的代码
# 示例:try:print(num) # 未定义numexcept NameError: # 变量名未定义错误print("有错误")
捕获多个指定异常
当捕获多个异常时,把要捕获的异常类型名字,用元组的方式放到**except**后。try:print(1 / 0)except (NameError, ZeroDivisionError):print("error") # error
捕获异常描述信息
try:代码except xxx as xxx:代码
try:print(1 / 0)except (NameError, ZeroDivisionError) as result: # 捕获错误描述信息到resultprint(result) # division by zero
捕获所有异常
**Exception**是所有程序异常类的父类。try:print(num)except Exception as result:print(result) # name 'num' is not defined
异常的
elseelse表示的是,如果没有异常要执行的代码。try:print(1) # 1except Exception as result:print(result)else:print("no error") # no error
异常的
finallyfinally表示的是,无论是否报异常,最终都要执行的代码。try:fo = open("test.txt", "r")except Exception as result:fo = open("test.txt", "w")print("新建文件")else:print("正常打开文件")finally:fo.close()print("关闭文件")
异常的传递(嵌套异常捕获)
```python import time
try: fo = open(“test.txt”, “r”) try: while True: content = fo.readline() if len(content) == 0: break time.sleep(1) print(content) # 每秒钟打印一行数据 except: print(“程序被中断!请重启后再试。”) # 用户主动终止时,报异常 finally: fo.close() print(“关闭文件!”) except: print(“文件打开失败!”)
<a name="jEwEj"></a># 自定义异常在Python中,抛出自定义异常的语法是`raise`异常类对象。- **自定义异常类继承于**`**Exception**`。```python"""实现输入长度不足报异常"""defLength = 3 # 定义默认长度# 自定义异常类,继承于Exceptionclass ShortInputError(Exception):def __init__(self, length, min_len):self.length = length # 实际长度self.min_len = min_len # 默认最小长度# 设置抛出异常的描述信息def __str__(self):return f"您输入的长度是{self.length},小于{self.min_len},请重新输入!"def main():try:pwd = input("请输入密码:")if len(pwd) <= defLength:raise ShortInputError(len(pwd), defLength) # 使用raise抛出异常except Exception as result:print(result) # 抛出异常描述信息else:print("密码输入已完成!")main()
