python - 我可以在 try-except block 中获取其中一项 Assets 的字符串吗?

标签 python python-3.x

我想检查一组输入,如果其中任何一个是非法的,我就会抛出一个错误并发出警告,所以我想让这个警告更习惯于找出哪个是错误的。

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/

相关文章:

python - 无法从 Windows10 上的 'ft2font' 导入名称 'matplotlib'

python - 使用 Linux 命令行发布表单和上传文件

python - Beautiful Soup .text 和标签仍然附加

python - Matplotlib 中三角形边框的问题

python-3.x - 我们如何在python中以圆周运动旋转图像

python - 使用pympler识别哪些变量在python中泄漏内存

python pygame 输入控件

python - 按两个元素分组的数据帧统计信息

python - 发生错误时更改变量而不终止程序

python - 一列的 Pandas 平均值,按其他列的值