[Python学习笔记][第八章Python异常处理结构与程序调试]

1/30

第八章Python异常处理结构与程序调试

异常处理

try…except结构

try:
    try块
except Exception:
    except块

try…except…else结构

try:
    try块
except Exception:
    except块
else:           #如果都没捕获到
    else块

带有多个except的try结构

try:
    try块
except Exception:
    except块
except Exception2:
    except块
else:           #如果都没捕获到
    else块

try..except..finally结构

try:
    try块
except Exception:
    except块
except Exception2:
    except块
else:           #如果都没捕获到
    else块
finally:        #无论如何都执行
    finally块

断言与上下文管理

assert   expression[,reason]

当判断表达式expression为真时,什么都不做,如果表达式为假时,则抛出异常

断言和异常处理结构往往结合使用,例如
try:
assert 1==2,”1 is not equal 2!”
except AssertionError:
print(“23123”)

with

with context_expr[as var]:
    with块

自动管理资源 保证资源的释放,常用在文件操作,网络通信

使用sys模块回溯最后的异常

PDB调试

原文地址:https://www.cnblogs.com/zy691357966/p/5480284.html