Python 中的异常处理

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

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 机制。让我们来看一个例子:

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 来捕捉不同类型的错误。至于我们的例子,如何处理不是数字的错误输入?

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 部分的代码。

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 块外编写代码的区别。

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 关键字如何?

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

相关推荐

  1. Python 异常处理

    2023-12-30 09:48:04       46 阅读
  2. Python异常处理

    2023-12-30 09:48:04       26 阅读
  3. Python错误和异常处理

    2023-12-30 09:48:04       13 阅读
  4. Python异常处理

    2023-12-30 09:48:04       16 阅读
  5. Python程序异常处理解决方法

    2023-12-30 09:48:04       36 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-30 09:48:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-30 09:48:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-30 09:48:04       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-30 09:48:04       20 阅读

热门阅读

  1. 【Go语言入门:Go语言的方法,函数,接口】

    2023-12-30 09:48:04       33 阅读
  2. 【C++ 单例模式】

    2023-12-30 09:48:04       39 阅读
  3. TCP/UDP协议

    2023-12-30 09:48:04       36 阅读
  4. 百度地图再vue中的引入方式

    2023-12-30 09:48:04       44 阅读
  5. 《基于 Vue 组件库 的 Webpack5 配置》- 总结

    2023-12-30 09:48:04       36 阅读
  6. FreeRTOS学习--61讲 内存管理

    2023-12-30 09:48:04       36 阅读
  7. 【蓝桥杯】比赛大纲整理

    2023-12-30 09:48:04       31 阅读