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"信息。

相关推荐
会飞锦鲤3 分钟前
基于 Mask R-CNN 的药片缺陷检测系统
人工智能·pytorch·python·神经网络·resnet-50
默 语6 分钟前
Java新手入门:从零开始安装JDK并配置环境变量
java·开发语言·python·mysql·group by·1024程序员节·数据去重
清水白石00837 分钟前
Python 异步编程深度解析:Cancellation 到底是异常还是控制信号?从 asyncio 取消机制到企业级事务设计最佳实践
开发语言·python
Patrick在香港1 小时前
Python 审计香港开放数据目录:两个端点差 10 倍,只有 9.3% 的资源标了「最后修改时间」
开发语言·数据库·python·数据分析·api·数据治理·开放数据
IT毕设梦工厂1 小时前
计算机毕业设计选题推荐:基于大数据的草鱼价格分析与可视化|毕业设计选题|计算机毕设|选题推荐|毕设指导|项目定制|源码|高质量项目
大数据·hadoop·python·数据挖掘·数据分析·课程设计·大数据毕设项目
GISHUB1 小时前
基于QGIS 3.44开发Python插件完整教程
python·qgis
大数据魔法师1 小时前
curl_cffi从入门到实战
爬虫·python
Sylvia33.1 小时前
火星数据体育API|一站式接入足球篮球电竞等18+项目实时数据
java·开发语言·python·websocket·游戏
程序员清风2 小时前
LangGraph 入门:用状态机设计可靠的 Agent 工作流
人工智能·python
Data_Journal2 小时前
使用 AutoScraper 进行网页抓取:分步教程
大数据·开发语言·数据库·python·scrapy