Python try except else使用详解
Python提供try except else语法结构用于异常处理、错误处理等场景。
try except else的基本用法
try except else 的语法形式如下:
try:
# 可能触发异常的代码
except 错误类型或异常 as 异常对象:
# 异常处理代码
else:
# 未触发异常时,执行的代码
finally:
# 不管是否有异常,都执行的代码
try 语句块中的代码是需要被监测的,如果该语句块中出现了异常,则会跳转到 except 语句块中进行异常处理;如果语句块正常执行,将跳转到 else 语句块中执行“未触发异常时,执行的代码”;然后无论是 try 代码块还是 except 代码块都执行完毕后,都将执行 finally 语句块中的代码。
例如,以下的代码将运行异常处理代码块:
try:
file = open('test.txt', 'rb')
except IOError as e:
print('An error occurred:', e)
else:
print('file opened successfully.')
finally:
print('This is always executed')
如果出错将输出:
An error occurred: [Errno 2] No such file or directory: 'test.txt'
This is always executed
如果文件存在就会输出:
file opened successfully.
This is always executed
try except else的示例
示例1:判断输入是否为数字
下面是一个用 try except else 语句结构来判断输入是否是数字的例子:
while True:
try:
x = int(input("请输入一个数字: "))
break
except ValueError:
print("您输入的不是数字,请再次尝试输入!")
finally:
print("finally子句需要被执行!")
print("输入的数字是: ", x)
程序的输出如下:
请输入一个数字: abcd
您输入的不是数字,请再次尝试输入!
finally子句需要被执行!
请输入一个数字: 5
finally子句需要被执行!
输入的数字是: 5
示例2:读取文件并统计其数字字符
以下示例读取名为“foo.txt”的文件并计算其中的数字字符数目:
import sys
file_name = "foo.txt"
try:
with open(file_name, 'r') as f:
lines = f.readlines()
except FileNotFoundError:
print("文件 %s 不存在,请检查文件名。" % file_name)
sys.exit()
nums = 0
for line in lines:
for char in line:
if char.isdigit():
nums += 1
print("文件 %s 中数字字符的数量为:%d" % (file_name, nums))
以上代码使用了 with 语句来处理文件读取,并且使用 except 语句在出现文件不存在的异常(FileNotFoundError)时及时通知用户。如果没有错误出现,程序将会统计文件中数字字符的出现次数并输出。
结论
Python try except else语法结构是Python中用于异常处理、错误处理等场景的必备语法,掌握这一语法可以让你写出更鲁棒的程序。