如何在此程序中发现错误?

时间:2019-03-05 12:18:26

标签: python python-3.x

我正在尝试在以下代码中捕获错误:

data.forEach { rule ->
    val view = layoutInflater.inflate(R.layout.rule_view_holder, null).apply {
        setOnClickListener { content.flipVisibility() }
        title.text = rule.title
        contentText.text = rule.content.fromHtml()
        rule.images.map {
            createImageView(this.context, it)
        }.forEach {
            contentImages.addView(it)
        }
    }
    this.rulesContainer.addView(view)
}

这是输出

n=int(input("enter the first number: "))
m=int(input("enter the second number: "))
p=n/m
try :
    print( n/m)
except :
    print("dividing by zero may not be possible")
print(p)

请指出我的错误。

3 个答案:

答案 0 :(得分:0)

您可以在将m分割或插入try子句之前检查p=n/m是否等于0。另外,您不想使用裸except,而是使用except ZeroDivisionError:之类的东西。

答案 1 :(得分:0)

n = int(input("enter the first number: "))
m = int(input("enter the second number: "))

try:
    p = n / m
    print(n / m)
    print(p)    
except ZeroDivisionError:
    print("dividing by zero may not be possible")

答案 2 :(得分:0)

您正在计算try / except块之外的p。只需在try块内添加p = n / m,所以如果抛出异常,它将由except块处理。将try块视为一个盒子,如果盒子内部发生爆炸,则可以处理,如果超出盒子外部,则无法处理。

此外,建议您指定要尝试捕获的异常类型,因为可能会发生许多异常,例如“除以零”,“除以非数字”等...似乎没有必要但是当您有很多代码时,它对调试很有帮助-否则,您将永远不知道为什么程序会失败。

n = int(input("enter the first number: "))
m = int(input("enter the second number: "))

try:
    p = n/m
    print(p)    
except ZeroDivisionError:
    print("dividing by zero may not be possible")
相关问题