python 示例_Python中带有示例的finally关键字

python 示例

Python最终关键字 (Python finally keyword)

finally is a keyword (case-sensitive) in python, it is a part of "try...except...finally" block, it is used to define a block (of coding statements) to execute finally i.e. no matter there is an exception or not in the "try" block. The finally block executes in any case.

最终是python中的一个关键字(区分大小写),它是“ try ... except ... finally”块的一部分,用于定义一个(编码语句的)块最终执行,即无论是否存在“ try”块中是否存在异常。 无论如何, finally块都会执行。

Syntax of finally keyword

finally关键字的语法

    try:
        statement(s)-1
    except:
        statement(s)-2
    finally:
        statement(s)-3

While executing the statement(s)-1, if there is any exception raises, control jumps to except block and statement(s)-2 executes, in case of finally block – no matter there is an exception in try block or not, statement(s)-3 executes in any case.

在执行语句-1时 ,如果引发任何异常,则控制跳至除了block之外的语句 ,并且在finally块的情况下执行语句2 –无论try块中是否存在异常, 语句(s)-3在任何情况下都会执行。

Example:

例:

    Input:
    a = 10
    b = 0

    try:
        # no error
        result = a%b
        print(result)
    
    except:
        print("There is an error")
    finally:
        print("Finally block, Bye Bye")

    Output:
    There is an error
    Finally block, Bye Bye

最终关键字的Python示例 (Python examples of finally keyword)

Example 1: Find modulus of two number and handle exception, if divisor is 0.

示例1:如果除数为0,则求两个数的模数并处理异常。

# python code to demonstrate example of 
# try, except, finally keyword 

# Find modulus of two number and 
# handle exception, if divisor is 0

a = 10
b = 3

try:
    # no error
    result = a%b
    print(result)
    
    # assign 0 to b
    # an error will occur
    b = 0
    result = a%b
    print(result)
    
except:
    print("There is an error")
finally:
    print("Finally block, Bye Bye")

Output

输出量

1
There is an error
Finally block, Bye Bye	


翻译自: https://www.includehelp.com/python/finally-keyword-with-example.aspx

python 示例

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值