python try 和
Python try关键字 (Python try keyword)
try is a keyword (case-sensitive) in python, it is a part of "try...except" block, it is used to define a block (of coding statements) to test/check whether this block contains an exception or not. If try block contains an exception program's control moves to the except block.
try是python中的一个关键字(区分大小写),它是“ try ... except”块的一部分,用于定义(编码语句的)块来测试/检查该块是否包含异常。 如果try块包含异常,程序的控制权将移至except块 。
Syntax of try keyword
try关键字的语法
try:
statement(s)-1
except:
statement(s)-2
While executing the statement(s)-1, if there is any exception raises, control jumps to except block and statement(s)-2 executes.
在执行语句-1时 ,如果引发任何异常,则控制跳转到块和语句2 除外 。
Example:
例:
Input:
a = 10
b = 0
try:
# no error
result = a%b
print(result)
except:
print("There is an error")
Output:
There is an error
try关键字的Python示例 (Python examples of try 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 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")
Output
输出量
1
There is an error
翻译自: https://www.includehelp.com/python/try-keyword-with-example.aspx
python try 和