Python 中的异常处理

Python 中的异常处理(Exceptions Handling in Python)

文章目录

  • [Python 中的异常处理(Exceptions Handling in Python)](#Python 中的异常处理(Exceptions Handling in Python))
    • [Introduction 导言](#Introduction 导言)
    • [Python 中的异常处理结构 Exceptions Handling Structure in Python](#Python 中的异常处理结构 Exceptions Handling Structure in Python)
    • [为什么我们需要 Finally 块?](#为什么我们需要 Finally 块?)

Introduction 导言

在编程过程process of programming中,我们总会遇到各种各样的错误errors。有些错误是由我们的代码造成的。比如语法错误syntax error。这种错误通常被称为 bug。必须对错误进行修复fixed。

但是,没有错误bug-free的程序仍然可能出现问题。因为有些错误并不是我们的代码造成的。它们可能是由意外情况accidental situations或操作operations引起的。这类错误被称为异常exceptions。例如:

  • 向文件写入数据时,磁盘可能已满,无法写入。
  • 在下载数据时,网络突然中断。
  • 除法时,输入 0 作为分母。
  • ...

健壮的代码不仅没有错误,还能很好地处理异常handling exceptions well。

Python 中的异常处理结构 Exceptions Handling Structure in Python

幸运的是Fortunately,Python 有一个内置的异常处理机制built-in exception handling mechanism,可以帮助我们方便地处理异常。它就是 try...except...finally 机制。让我们来看一个例子:

python 复制代码
a = input("Please enter the Numerator: ")
b = input("Please enter the Denominator: ")
try:
    r = int(a) / int(b)
    print('result:', r)
except ZeroDivisionError as e:
    print('except:', e)
finally:
    print('The End')
    
# Please enter the Numerator: 5
# Please enter the Denominator: 0
# except: division by zero
# The End

# Please enter the Numerator: 1
# Please enter the Denominator: 2
# result: 0.5
# The End

如上例所示,当我们考虑到代码的某些部分可能会发生异常may occur exceptions时,可以将其放入 try 语句中。如果异常真的发生了, except 语句块statement block中的代码就会运行。最后Finally,无论异常是否发生, finally 语句块中的代码都将运行。

错误应该有多种类型many types of errors。如果出现不同类型的错误,应该由不同的 except 块来处理。当然,也可以有多个 except 来捕捉不同类型的错误。至于我们的例子,如何处理不是数字的错误输入?

python 复制代码
a = input("Please enter the Numerator: ")
b = input("Please enter the Denominator: ")
try:
    r = int(a) / int(b)
    print('result:', r)
except ValueError as e:
    print('except:', e)
except ZeroDivisionError as e:
    print('except:', e)
finally:
    print('The End')
    
# Please enter the Numerator: Zhang
# Please enter the Denominator: 666
# except: invalid literal for int() with base 10: 'Zhang'
# The End

我们可以看到,如果输入一个字符串string作为分子numerator,就会出现 ValueError 。因此,我们的代码更加健壮,因为它可以处理两种类型的异常。

ValueErrorZeroDivisionError 是 Python 内置的错误对象build-in error objects。Python 错误对象的完整列表可以在 Python 文档Exception hierarchy中找到。

此外,我们还可以在 except 块之后添加一个 else 块。如果没有异常发生no exception happened,它就会运行 else 部分的代码。

python 复制代码
a = input("Please enter the Numerator: ")
b = input("Please enter the Denominator: ")
try:
    r = int(a) / int(b)
    print('result:', r)
except ValueError as e:
    print('except:', e)
except ZeroDivisionError as e:
    print('except:', e)
else:
    print("No exception!")
finally:
    print('The End')
    
# Please enter the Numerator: 2
# Please enter the Denominator: 4
# result: 0.5
# No exception!
# The End

注意: else 块将在没有异常情况发生时运行。而 finally 块无论发生什么情况都会运行。

为什么我们需要 Finally 块?

如上所述, finally 块无论如何都会运行。当我们需要确保无论是否遇到异常exceptions都会完成某些操作时,这个功能就非常有用。例如,当我们打开一个文件并对其进行一些操作operations时,我们应该确保最终finally关闭该文件。

下面的示例说明了在 finally 块中编写代码与在 finally 块外编写代码的区别。

python 复制代码
a = input("Please enter the Numerator: ")
b = input("Please enter the Denominator: ")
try:
    r = int(a) / int(b)
    print('result:', r)
except ZeroDivisionError as e:
    print('except:', e)
    exit()
finally:
    print('The End')

# Please enter the Numerator: 8
# Please enter the Denominator: 0
# except: division by zero
# The End

如上所示,即使我们遇到 ZeroDivisionError ,并且其代码块中有 exit()finally 代码块中的代码仍将运行(print "The End")。

取消 finally 关键字如何?

python 复制代码
a = input("Please enter the Numerator: ")
b = input("Please enter the Denominator: ")
try:
    r = int(a) / int(b)
    print('result:', r)
except ZeroDivisionError as e:
    print('except:', e)
    exit()
print('The End')

# Please enter the Numerator: 8
# Please enter the Denominator: 0
# except: division by zero

在运行 print('The End') 之前,上述程序已经退出!不会打印 "The End"信息。

相关推荐
玄同765几秒前
Python Random 模块深度解析:从基础 API 到 AI / 大模型工程化实践
人工智能·笔记·python·学习·算法·语言模型·llm
AIFarmer5 分钟前
在EV3上运行Python语言——环境设置
python·ev3
yunsr10 分钟前
python作业3
开发语言·python
历程里程碑11 分钟前
普通数组-----除了自身以外数组的乘积
大数据·javascript·python·算法·elasticsearch·搜索引擎·flask
曦月逸霜11 分钟前
Python快速入门——学习笔记(持续更新中~)
笔记·python·学习
喵手14 分钟前
Python爬虫实战:采集菜谱网站的“分类/列表页”(例如“家常菜”或“烘焙”频道)数据,构建高可用的美食菜谱数据采集流水线(附CSV导出)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集菜谱网站数据·家常菜或烘焙频道·构建高可用食谱数据采集系统
喵手15 分钟前
Python爬虫实战:硬核解析 Google Chrome 官方更新日志(正则+文本清洗篇)(附 CSV 导出)!
爬虫·python·爬虫实战·零基础python爬虫教学·csv导出·监控谷歌版本发布历史·获取稳定版更新日志
小邓睡不饱耶18 分钟前
实战|W餐饮平台智能化菜品推荐方案(含Spark实操+算法选型+完整流程)
python·ai·ai编程·ai写作
草莓熊Lotso20 分钟前
Qt 主窗口核心组件实战:菜单栏、工具栏、状态栏、浮动窗口全攻略
运维·开发语言·人工智能·python·qt·ui
aiguangyuan24 分钟前
基于BiLSTM-CRF的命名实体识别模型:原理剖析与实现详解
人工智能·python·nlp