python 示例
Python关键字除外 (Python except keyword)
except is a keyword (case-sensitive) in python, it is used with try... except statement to handle the exception.
除了是python中的一个关键字(区分大小写),它与try ... except语句一起使用来处理异常。
except keyword defines a block which executes if statements are written in try block raise an error.
else关键字定义了一个块,如果在try块中编写了语句,该块将执行,并引发错误。
Note: We can define multiple blocks with except keyword to handle the different types of expectations by mentioning the error/exception names.
注意:我们可以通过提及错误/异常名称,使用except关键字定义多个块以处理不同类型的期望。
Syntax of except keyword
关键字除外的语法
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 除外 。
Syntax of except keyword with multiple except blocks
具有多个except块的except关键字的语法
try:
statement(s)-1
except Error_Name1:
statement(s)-A
except Error_Name2:
statement(s)-B
except Error_Name3:
statement(s)-C
..
except:
statement(s)-default
While executing the statement(s)-1 if Error_Name1 generates, statements written in Except Error_Name1 (statements(s)-A) executes, and so on... If any error is not mentioned with except block then last except block without any error name executes.
如果Error_Name1生成,则在执行语句-1时,将执行用Error_Name1 以外的语句编写的语句( 语句-A ),依此类推...如果未提及任何错误,则除了block 以外,最后一个exception 都没有错误名称执行。
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
Python的除外关键字示例 (Python examples of except keyword)
Example 1: Find modulus of two number and handle exception, if divisor is 0.
示例1:如果除数为0,则求两个数的模数并处理异常。
# python code to demonstrate example of
# 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
Example 2: Write an example to handle multiple errors.
示例2:编写示例以处理多个错误。
# python code to demonstrate example of
# except keyword
# Write an example to handle multiple errors
a = 10
b = 3
try:
# del b # uncomment this to test NameError
# no error
result = a%b
print(result)
# assign 0 to b
# an error will occur
b = 0
result = a%b
print(result)
except ZeroDivisionError:
print("Can not divide by 0")
except NameError:
print("A NameError in the code")
except:
print("There is an error")
Output
输出量
1
Can not divide by 0
翻译自: https://www.includehelp.com/python/except-keyword-with-example.aspx
python 示例