python学习笔记(12月28日)-python异常

当电脑中没有a.txt这个文件时,

try:

f=open('a.txt','r')

except TypeError:

print('no file.')

输出

====================== RESTART: C:/Python34/xuexi/1.py ======================Traceback (most recent call last):  

File "C:/Python34/xuexi/1.py", line 2, in

f=open('a.txt','r')

FileNotFoundError: [Errno 2] No such file or directory: 'a.txt'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):  File "C:/Python34/xuexi/1.py", line 3, inexcept typeerror:

NameError: name 'typeerror' is not defined


TypeError改为FileNotFoundError

try:

f=open('a.txt','r')

except TypeError:

print('no file.')

输出

no file.

>>>


当文件存在时,输出为2.txt的内容


try:

f=open('2.txt','r')

print(f.read())

f.close()

except TypeError:

print('no file.')

输出

ID

age

abc

>>>        


当文件存在时,      

try:

f=open('2.txt','r')

print(f.read())

except IOError:

print('no file.')

except TypeError:

print('type error.')

except:

print("other error.")

else:

print("file exist")

finally:

print("done")

输出

ID

age

abc

file exist

done

>>>


当文件不存在时,

try:

f=open('2q.txt','r')

print(f.read())

except IOError:

print('no file.')

except TypeError:

print('type error.')

except:

print("other error.")

else:

print("file exist")

finally:

print("done")

输出

no file.

done

>>>


import traceback

try:

a=b

b=c

except:

f=open('log.txt','a')       #a附加

f.flush()                        #flush 写入缓存

traceback.print_exc(file=f)

finally:

print("save log.")

f.close()

输出

save log.

>>>



a=None

try:

if a=='None':

raise Exception("not object")    #不管有没有,都定义为异常

print("a is null")

except:

print("error")

finally:

print("Done")

输出

Done

>>>


import time

try:

f=open('1.txt')

while True:

line =f.readlines()      #当有1.txt这个文件时,输出结果

if len(line)==0:        #如果行等于0

break

time.sleep(2)          #等2秒

print(line)

finally:

f.close()

输出

['ID\n', 'age\n', 'aaa']

>>>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容