程序说明:
程序接受一个文件名和一个段,该段由两个数字组成(每个数字除以一个空格)。然后,它从现有文件中输出所有行,其索引位于给定的段内。
我的解决方案:
import sys
try:
par = input("Input (<file> <low border of the segment> <high border of the segment>): ").split(' ')
print(17 * '-')
f = par[0]
f_lines = [line.strip("\n") for line in f if line != "\n"]
length = len(f_lines)
if (par == ''):
raise RuntimeError('Error: undefined')
if (par[2] == None) or (par[2] == ''):
raise RuntimeError('Error: segment is limited')
if ((par[1] and par[2]) == None) or ((par[1] and par[2]) == ''):
raise RuntimeError('Error: segment undefined')
if (int(par[2]) >= length):
raise RuntimeError('Error: segment can not be greater than length the amount of lines')
if (par[1] == ''):
a = 0
if (par[2] == ''):
b = 0
segment = [int(par[1]), (int(par[2]) + 1)]
with open(par[0]) as f:
data = f.read().splitlines()
for k in range(segment[0], segment[1]):
print(data[k])
except (FileNotFoundError, IOError, NameError):
print('[!] Error: your input is incorrect. The file may be missing or something else. \n[?] For further information see full error logs: \n',sys.exc_info())
except RuntimeError as e:
print(e)
问题:
当我尝试以不同的方式运行程序以测试每个运行时错误时,总是收到以下消息:
Traceback (most recent call last):
File "C:\Users\1\Desktop\IT\pycharm\sem_2.py", line 10, in <module>
if (par[2] == None) or (par[2] == ''):
IndexError: list index out of range
我不能全神贯注于如何正确处理多个运行时错误,使它们显示为文本消息。在网上的任何地方都找不到针对我的问题的任何解决方案,因此我想在这里提出。
我将不胜感激,在此先感谢您。
您的代码会赶上FileNotFoundError
,IOError
,NameError
和RuntimeError
,但什么是真正抛出的IndexError
,因此不处理。
您可能需要将IndexError
其添加到第一个except
块:
except (FileNotFoundError, IOError, NameError, IndexError):
print('[!] Error: input incorrect!') # ^^^^^^^^^^^^
或者,except
如果您想为IndexError
以下内容添加自定义消息,则可以添加另一个块:
except (FileNotFoundError, IOError, NameError):
print('[!] Error: input incorrect!')
except IndexError:
print('[!] Error: IndexError just happened!')
顺便说一句,以下内容始终是False
因为括号中的代码将解析为bool
第一个,可以是True
或,False
而这些绝不等于''
或None
:
((par[1] and par[2]) == None) or ((par[1] and par[2]) == '')
您可能希望将其重写为:
(par[1] is None and par[2] is None) or (par[1] == '' and par[2] == '')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句