抱歉,您的浏览器无法访问本站

本页面需要浏览器支持(启用)JavaScript


了解详情 >

try:, except … as …:

错误处理

输出错误:try:, except ... as ...: 看如下代码

1
2
3
4
try:
file=open('eeee.txt','r') #会报错的代码
except Exception as e: # 将报错存储在 e 中
print(e)
[Errno 2] No such file or directory: 'eeee.txt'
1
2
3
4
5
6
7
8
9
10
11
12
try:
file=open('eeee.txt','r+')
except Exception as e:
print(e)
response = input('do you want to create a new file:')
if response=='y':
file=open('eeee.txt','w')
else:
pass
else:
file.write('ssss')
file.close()
[Errno 2] No such file or directory: 'eeee.txt'
do you want to create a new file:y

Reference