我想检查一组输入,如果其中任何一个是非法的,我就会抛出一个错误并发出警告,所以我想让这个警告更习惯于找出哪个是错误的。
try:
assert input1<1 something like this, "input1 error xxx"
assert input2 xxx, "input2 error xxx"
xxxx
except AssertionError:
make a warning dialog using the assert infomation
except:
pass
else:
pass
这可能吗?我想我可以避免多个 try-except block 或 if block ,是否有 pythonic 方法来做到这一点?提前谢谢你。
得到它。感谢您的帮助。断言不应用于测试。我现在将修改我的代码。
最佳答案
您为什么不尝试创建自己的自定义异常并在您的条件失败时抛出它。然后你就可以捕获它了。这样做的好处在于,即使您的代码抛出一些内部错误,您也会知道如何处理它。
class MyException(Exception):
pass
....
try:
#if some condition
raise MyException()
except MyException:
#handle this exception
或者因为你正在处理测试用例
def mytest(self):
with self.assertRaises(MyException):
#some if condition
raise MyException()
关于python - 我可以在 try-except block 中获取其中一项 Assets 的字符串吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43474859/