0
点赞
收藏
分享

微信扫一扫

1697_python编程_assertions and exceptions

小猪肥 2023-05-02 阅读 67

全部学习汇总: GreyZhang/python_basic: My learning notes about python. (github.com)

这部分主要关于程序中的异常类型以及处理方式

exception:

常见的异常类型(exceptions)有几种:索引错误、类型错误、名字错误、混合类型错误。对应这几种分类,给出以下几个例子:

索引错误(列表等数组类变量越界)

>>> test = [1,2,3]

>>> test[4]

Traceback (most recent call last):

  File "<pyshell#1>", line 1, in <module>

    test[4]

IndexError: list index out of range

类型错误

>>> int(test)

Traceback (most recent call last):

  File "<pyshell#3>", line 1, in <module>

    int(test)

TypeError: int() argument must be a string or a number, not 'list'

名字错误

>>> a

Traceback (most recent call last):

  File "<pyshell#4>", line 1, in <module>

    a

NameError: name 'a' is not defined

没有进行强制类型转换的混合类型会引发一个类型错误:

>>> 'a'/4

Traceback (most recent call last):

  File "<pyshell#5>", line 1, in <module>

    'a'/4

TypeError: unsupported operand type(s) for /: 'str' and 'int'

处理方式:

1,不处理,直接放过

2,返回一个错误值

3,停止执行,抛出一个异常

异常的捕捉

使用try语句可以捕捉到异常句柄。

例如:

try:

f = open(‘test.txt’)

# code to read and process test.txt

except:

raise Exception(“can’t open files”)

以上程序执行时,如果test.txt不存在或者因为某种原因无法打开,将会抛出一个异常提示文件打不开。

assertion:

捕捉我们已知或者假设的某些异常,可以使用assert语句。示例如下:

>>> def avg(grades,weights):

         assert not len(grades) == 0, 'no grades data'

         print "test"

        

>>> avg([],123)

Traceback (most recent call last):

  File "<pyshell#4>", line 1, in <module>

    avg([],123)

  File "<pyshell#3>", line 2, in avg

    assert not len(grades) == 0, 'no grades data'

AssertionError: no grades data

>>> avg([1,2,3],3)

Test

使用assert,可以比较方便地按照我们自己制定的提示需求来给我们提示相应的异常或者错误。

assert常用的一些场景:

检查参数的类型或者数值

检查遇到的数据结构的变化

检查返回值的约束条件

检查函数约束条件的变化(例如:列表不是复数形式)

小结:

异常与错误处理在程序中并不一定是必需的,并且这回在一定程度上拖慢程序执行的效率。但是这会是程序可靠性提升的一个保障,在编写可靠稳定的处理程序时这通常会是不可缺少的一个环节。

举报

相关推荐

JUnit5学习之三:Assertions类

0 条评论