五种异常处理机制:默认异常处理、assert与with...as

默认异常处理机制:

yc.py
s=[1,2,3] print(s[100])
print(s[0])

输出结果: Traceback (most recent call last): File
"<pyshell#1>", line 1, in <module> s[100] IndexError: list index out of range >>>

如果我们没有对异常进行任何预防,那么在程序执行的过程中发生异常,就会中断程序,调用python默认的异常处理器,并在终端输出异常信息。这种情况下,第3行代码不会执行。

assert(断言)异常步骤机制:

断言(assert): 就是判断expression 这个表达式语句是否正确,所以切记,断言是有一个判断的过程!!!

格式:

assert expression, 'information'

解释:
expression 表达式其实是相当于一个 if 判断,如果表达式返回的是True,则程序继续向下执行,如果返回的是False,则会报出 AssertionError 断言错误,和断言错误信息information

>>> def testAssert(x):
    assert x < 1, "Invalid value"
    print("程序无异常才会执行到这里")

    
>>> testAssert(2) #执行异常
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    testAssert(2)
  File "<pyshell#3>", line 2, in testAssert
    assert x < 1, "Invalid value"
AssertionError: Invalid value

>>> testAssert(0) #执行无异常
程序无异常才会执行到这里
>>> 

with...as

*使用with自动关闭资源,可以再代码块执行完毕后还原进入该代码块时的现场。
*不论何种原因跳出with块,不论是否发生异常,总能包种文件关闭时,资源被正确释放。

*with语句的语法:
  with context_expr [as var]:
    with块

with open('d:/leninor.txt','r')as f:
        for line in f:
                print(line)
#leninor.txt内容:12234

输出结果:

=================== RESTART: C:UsersadminDesktopyc.py ===================
12234
>>>

原文地址:https://www.cnblogs.com/bashliuhe/p/12734762.html