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

相关推荐
liuzhenghua6625 分钟前
Python任务调度模型
java·运维·python
小前端大牛马35 分钟前
java教程笔记(十一)-泛型
java·笔记·python
sjtu_cjs37 分钟前
Tensorrt python api 10.11.0笔记
开发语言·笔记·python
哆啦A梦的口袋呀41 分钟前
深入理解系统:UML类图
开发语言·python·uml
虎冯河1 小时前
怎么让Comfyui导出的图像不包含工作流信息,
开发语言·python
葬爱家族小阿杰2 小时前
python执行测试用例,allure报乱码且未成功生成报告
开发语言·python·测试用例
xx155802862xx2 小时前
Python如何给视频添加音频和字幕
java·python·音视频
酷爱码2 小时前
Python实现简单音频数据压缩与解压算法
开发语言·python
花果山总钻风2 小时前
SQLAlchemy 中的 func 函数使用指南
python
知识中的海王2 小时前
Python html 库用法详解
开发语言·python