![](/img/trans.png)
[英]Python: try-catch-else without handling the exception. Possible?
[英]Converting My Error Checker To A `try-catch-else `
我下面有一些代码用于检查列表列表是否包含空字符串。 在上下文中,我的应用程序的用户将填写调查问题,但如果他们将调查问题之一留空,那么我想提醒他们他们需要返回并填写调查。 我需要在一堆不同的地方执行这个检查,所以我认为一个类将是一个很好的用例,以提高我的程序的可读性和可移植性。
然而,我开始学习 try-except 块,并认为它可能是我代码本质的更好地方。 但是我在将我的简单类转换为 try-except 块时遇到了一些问题,如果可以的话,我想尝试以这种方式实现它。 但是,我认为我想做的事情可能不适合尝试测试块,所以我希望得到一些反馈。
class ErrorCheck():
def __init__(self, survey_responses):
self.survey_responses = survey_responses
def check_empty(self):
for item in self.survey_responses:
if '' in item:
print('One of these is empty')
x = ErrorCheck([['abc'],[2],['apples'],['']])
x.check_empty()
您尝试实现的代码非常正确。 除了如果您想突出显示错误,而不是仅使用print
函数,请使用raise Exception()
并在括号中插入一个字符串,在您的情况下为“其中一个为空”。
这将导致如下输出: Exception: One of these is empty
这可能是你正在寻找的。
正如其他人已经指出的那样,您想要做的可能是raise
异常,在raise
异常后,您可以在try
... except
块中捕获它并对其进行处理:
survey_responses = ['a','','c']
def check_empty(responses):
for response in responses:
if response == '':
raise Exception('Missing Answer: One or more answers are empty')
try:
check_empty(survey_responses)
except Exception as exc:
print(exc)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.