📜  Python|断言错误

📅  最后修改于: 2022-05-13 01:54:41.215000             🧑  作者: Mango

Python|断言错误

断言错误
断言是在编写代码时使用的编程概念,其中用户在运行模块之前使用断言语句声明条件为真。如果条件为True ,则控件只是移动到下一行代码。如果为False ,程序将停止运行并返回AssertionError异常。

assert语句的函数与实现它的语言无关,它是一个与语言无关的概念,只是语法因编程语言而异。

断言语法:
断言条件,error_message(可选)

示例 1:带有 error_message 的断言错误。

Python3
# AssertionError with error_message.
x = 1
y = 0
assert y != 0, "Invalid Operation" # denominator can't be 0
print(x / y)


Python3
# Handling it manually
try:
    x = 1
    y = 0
    assert y != 0, "Invalid Operation"
    print(x / y)
 
# the errror_message provided by the user gets printed
except AssertionError as msg:
    print(msg)


Python3
# Roots of a quadratic equation
import math
def ShridharAcharya(a, b, c):
    try:
        assert a != 0, "Not a quadratic equation as coefficient of x ^ 2 can't be 0"
        D = (b * b - 4 * a*c)
        assert D>= 0, "Roots are imaginary"
        r1 = (-b + math.sqrt(D))/(2 * a)
        r2 = (-b - math.sqrt(D))/(2 * a)
        print("Roots of the quadratic equation are :", r1, "", r2)
    except AssertionError as msg:
        print(msg)
ShridharAcharya(-1, 5, -6)
ShridharAcharya(1, 1, 6)
ShridharAcharya(2, 12, 18)


输出 :

Traceback (most recent call last):
  File "/home/bafc2f900d9791144fbf59f477cd4059.py", line 4, in 
    assert y!=0, "Invalid Operation" # denominator can't be 0
AssertionError: Invalid Operation

Python中的默认异常处理程序将打印程序员编写的error_message,否则将只处理错误而没有任何消息。
两种方式都有效。

处理 AssertionError 异常:
AssertionError继承自 Exception 类,当此异常发生并引发 AssertionError 时,有两种处理方式,用户处理或默认异常处理程序。
在示例 1 中,我们看到了默认异常处理程序是如何工作的。
现在让我们深入研究手动处理它。

示例 2

Python3

# Handling it manually
try:
    x = 1
    y = 0
    assert y != 0, "Invalid Operation"
    print(x / y)
 
# the errror_message provided by the user gets printed
except AssertionError as msg:
    print(msg)

输出 :

Invalid Operation

实际应用。
示例 3:测试程序。

Python3

# Roots of a quadratic equation
import math
def ShridharAcharya(a, b, c):
    try:
        assert a != 0, "Not a quadratic equation as coefficient of x ^ 2 can't be 0"
        D = (b * b - 4 * a*c)
        assert D>= 0, "Roots are imaginary"
        r1 = (-b + math.sqrt(D))/(2 * a)
        r2 = (-b - math.sqrt(D))/(2 * a)
        print("Roots of the quadratic equation are :", r1, "", r2)
    except AssertionError as msg:
        print(msg)
ShridharAcharya(-1, 5, -6)
ShridharAcharya(1, 1, 6)
ShridharAcharya(2, 12, 18)

输出 :

Roots of the quadratic equation are : 2.0  3.0
Roots are imaginary
Roots of the quadratic equation are : -3.0  -3.0

这是一个示例,说明此异常如何在断言条件为 False 时立即停止程序的执行。

其他有用的应用:

  • 检查参数值。
  • 检查有效的输入/类型。
  • 检测另一个程序员滥用接口。
  • 检查函数的输出。