Catch exception

abnormal

An exception is an event that occurs during program execution and affects the normal execution of the program. Under normal
circumstances, an exception occurs when python cannot handle the program normally.
The python object in the case of an exception indicates an error.
When an exception occurs in the python script, we need to catch and handle it, otherwise the program will terminate its execution.

Basic format for catching exceptions

try:
    语句一   # 检测语句一是否存在错误
except 异常名称:
    语句二  # 若语句一存在错误,可捕获错误
finally:
    语句三  # 无论是否存在错误,都会被执行finally内代码

Common mistakes

常见异常名称
    BaseException       所有异常错误
    Exception           常规错误
    ZeroDivisionError   除0异常错误
    ValueError          值类型异常错误

For more abnormal errors, please check: http:///www.runoob.com/python/python-exeptions.html

raise raise an exception

We can explicitly raise an exception through raise
Once the exception behind raise is raised, the program execution will be terminated

# 需求
# 1、传入一个参数,判断是否为整形类型,如果不是,则抛出异常,终止程序
# 2、判断是否大于等于5,如果小于5,则抛出异常终止程序
def  f2(num):
    if not isinstance(num,int):
        raise Exception("该参数不是一个整形类型")
    if num<5:
        raise Exception("改参数小于5")
    print("The number of sending by you is: %d" %num)

f2('b')

assert

The exception parameter of assert starts with the Tianjian string information after the assertion expression, which is used to explain the assertion and better know where the problem occurred.
Basic format assert bool_expression [,arguments]

If: bool_expression is False, the custom exception information of arguments will be thrown.
If: bool_expression is True, the custom exception information of arguments will not be thrown.

# 需求
# 1、传入一个参数,判断是否为整形类型,如果不是,则抛出异常,终止程序
# 2、判断是否大于等于5,如果小于5,则抛出异常终止程序
def  f2(num):
    assert isinstance(num,int), "改参数不是一个整形类型"
    assert num>=5, "改参数小于5"
    print("The number of sending by you is: %d" %num)


f2(2)

Guess you like

Origin blog.csdn.net/Mwyldnje2003/article/details/113426541