python遇到错误时怎么让程序重新执行?
连try都没法捕获这种错误吗,程序直接停了
try: with open('','r', encoding='utf-8') as file:
content = file.read()
print(content)
except Err:
print("出错了")
with open('','r', encoding='utf-8') as file:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: ''
回答:
指定文件错误类 FileNotFoundError
就能捕获,如果题主是需要通用错误捕获也是 Exception
,我印象中没有 Err
这个错误类
python">try: with open('', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
except FileNotFoundError:
print("文件不存在")
# 或者捕获全部错误
try:
with open('', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
except Exception:
print("文件不存在")
以上是 python遇到错误时怎么让程序重新执行? 的全部内容, 来源链接: utcz.com/p/938992.html