python-20 异常处理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/L1558198727/article/details/83621552

在python程序设计中,常见的错误类型

语法错误:
	syntaxError
	代码的拼写错误
	又叫编译错误
运行时错误
	在解释执行的时候出现的错误
	除数为零
	导入的包不存在
	打开的文件不存在
逻辑错误
	程序可以正常运行,但是结果不正确
	python无法解决,可以正常运行,只是结果不对

异常处理机制


	

java里面:
可以写多个异常类
用 | 隔开



python里面的异常父类

BaseException
Exception SystemExit KeyboardInterrupt GeneratorExit

(1)NameError 尝试访问未命名的变量
(2)SyntaxError  语法错误
(3)AttributeError 访问未知对象的属性
(4)TypeError 类型错误
(5)ValueError 数值错误
(6)ZeroDivisionError 除零错误
(7)IndexError 索引超过边界
(8)KeyError 字典关键字不存在

raise

抛出异常:
Eg:

a = -9
if a<0 :
    raise ValueError("数字不能是复数")

结果:
ValueError: 数字不能是复数

python里面的异常处理

python里面只能写一个
try:
	可能产生异常的语句
except FileNotFoundException:
	捕获异常的语句
except otherException:
	捕获异常的语句
else:	
	没有发生异常的时候执行的语句
finally:
	一定会执行的语句,不管是否产生异常


一个例子

try:
    f = open("test.txt","r")
    f.write("这个是测试的内容")
    f1 = open("test1.txt","r")
except IOError:
    print("没有找到文件")
else:
    print("文件写入成功")

finally:
    f.close()

将子类的异常放在前面

a = (-1,2,-3,4,5)
sum = 0

try:
    for i in a:
        if i<0:
            raise ValueError( str(i) + "<0")
        sum += i
    print("",sum)
except ValueError:
    print("发生异常")
except Exception:
    print("发生异常(父类)")
else:
    print("没有异常")

finally:
    f.close()

自定义异常类

1.都要继承 Exception 或者 Exception的子类
2.命名一般都是Error或者Exception为后缀

class NumberError(Exception):
    def __init__(self,data):
        Exception.__init_(self,data)
        self.data = data

    def __str__(self):
        return self.data + "非法数值"

def total(data):
    total = 0;
    for i in data:
        if i<0:
            raise NumberError(str(i))
        total += i
    return total

断言

断言的一般形式:
1.前置条件断言
2.后置条件断言
3.前后不变断言


声明的形式
assert 布尔类型的表达式
assert 布尔类型的表达式,字符串表达式

python的解释器

python的解释器有两种运行模式,调试模式和优化模式
通常为调试模式 内置只读变量__debug__ 的值为true
但是如果使用选项-o运行时,则改为优化模式,__debug__的值为false

if __debug__:
	if not testexpression:raise AssertionError


if __debug__:
	if not testexpression:raise AssertionError if __debug__:
		if not testexpression raise AssertionError(data)

使用 -o运行,优化模式运行

python -o test.py

断言扩展

assert 布尔类型的表达式 
assert 布尔类型的函数 (用的比较少)

改进断言

开源的测试框架
py.test 轻量级的测试框架
利用python的断言对测试进行更加直观性的说明

1.安装
pip install -U pytest

--version 查看版本

2.
import pytest
def test_case():
    expected = 'Hello'
    actual = 'hello'
    assert expected == actual

if __name__=='__main__':
    pytest.main()

运行:
py.test test.py

__________________________________ test_case __________________________________

    def test_case():
        expected = 'Hello'
        actual = 'hello'
>       assert expected == actual
E       AssertionError: assert 'Hello' == 'hello'
E         - Hello
E         ? ^
E         + hello
E         ? ^

test.py:5: AssertionError
========================== 1 failed in 0.09 seconds ===========================

北方用 unittest

python 自带的单元测试框架

不推荐使用assert 语句 而是使用断言方法 self.assertXXX()


import unittest
class TestStringMethod(unittest.TestCase):
    
    def test_upper(self):
        self.assertEqual('foo'.upper(),'FoO')

if __name__=='__main__':
    unittest.main()

结果:
F
======================================================================
FAIL: test_upper (__main__.TestStringMethod)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\li_yu\Desktop\test.py", line 5, in test_upper
    self.assertEqual('foo'.upper(),'FoO')
AssertionError: 'FOO' != 'FoO'
- FOO
?  ^
+ FoO
?  ^


----------------------------------------------------------------------
Ran 1 test in 0.022s

FAILED (failures=1)

ptest 测试框架

特点:既可以实现断言,并且声称测试报告,以图形化的方式展示

作者是 Karl 大神
作者简介:最初是java开发的,框架里面的语法很多沿用java的注解

运行:
python 2:
	ptest -t 文件名.类名.方法名
python 3:
	#测试类里面的所有方法
	ptest3 -t 文件名
	#测试指定的方法
	ptest3 -t 文件名.类名.方法名

会生成相应的测试报告

Eg:
from ptest.decorator import *
from ptest.assertion import *
@TestClass()
class TestCases:
    @Test()
    def test1(self):
        actual = 'foo'
        excepted = 'var'
        assert_that(excepted).is_equal_to(actual)

在这里插入图片描述

assertpy包

里面有很多写好的测试方法
不生成测试报告
安装
pip install assertpy


Eg:
from assertpy import assert_that

def test1():
    assert_that(1+2).is_equal_to(333)
    #assert_that()
if __name__ == '__main__':
    test1()

猜你喜欢

转载自blog.csdn.net/L1558198727/article/details/83621552