异常处理
*try - except 语句 :
try:
检测范围
except Exception[as reason]:
出现异常(Exception)后的处理代码*
1.错误提示
f = open('我为什么是一个文件.txt')
print(f.read())
f.close
===================== RESTART: D:/Python/Mypython/test2.py =====================
Traceback (most recent call last):
File "D:/Python/Mypython/test2.py", line 1, in <module>
f = open('我为什么是一个文件.txt')
FileNotFoundError: [Errno 2] No such file or directory: '我为什么是一个文件.txt'
>>>
2.加上try语句,可以执行,提示错误
try:
f = open('我为什么是一个文件.txt')
print(f.read())
f.close
except OSError:
print('文件出错啦!')
===================== RESTART: D:/Python/Mypython/test2.py ============<