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 示例