try: ... except Exception1: ... except Exception2: ... finally: ...
如果在try中发生错误,那么except将捕获到指定错误,然后执行该段语句;而无论有无错误finally都会执行.
#-*-coding=utf-8-*- a = 0 try: 10 / a except BaseException: print(‘a is 0‘) finally: print(‘done‘)
所有异常的异常都继承自BaseExecption,所以可以指定BaseExecption来捕获所有异常
raise为编程者手动抛出错误
格式:
raise 错误类型(错误信息)
注意,raise语句如果不带参数,就会把当前错误原样抛出或抛出No active exception to reraise
#-*-coding=utf-8-*- a = 0 try: if a == 0: raise ValueError(‘a is 0‘) 10 / a except Exception as e: print(e) finally: print(‘done‘)
assert a != 0, ‘a is 0‘
如果a不等于0,符合预期,否则输出a is 0
可以使用 -O来关闭assert输出:
python -O file.py
示例:
import logging logging.basicConfig(filename=‘log.log‘, level=logging.INFO) logging.info(‘发生错误‘)
self.assertEqual(abs(-1), 1) # 断言函数返回的结果与1相等
#断言是否会引发指定类型的错误 with self.assertRaises(KeyError): value = d[‘empty‘]
if __name__ == ‘__main__‘: unittest.main()
另一种方法是在命令行通过参数-m unittest直接运行单元测试,这样可以一次运行多个单元测试
import unittest def say_hello(): return ‘hello‘ def division(a): if a == 0: raise ValueError(‘a不能为0‘) return 100/a class Test(unittest.TestCase): def setUp(self): print(‘测试开始了‘) def test_say_hello(self): self.assertEqual(say_hello(), ‘hello‘) def test_division(self): with self.assertRaises(ZeroDivisionError): division(0) def tearDown(self): print(‘测试结束了‘) if __name__ == ‘__main__‘: unittest.main()
文档注释中写入交互命令,即可作为文档测试
class OK: """ this is test ok Example: >>> ok = OK() >>> ok.my(1,2) 30 >>> ok.my(2,-1) Traceback (most recent call last): ... Param is error: -1 """ def my(self, a, b): return a + b if __name__ == ‘__main__‘: import doctest doctest.testmod()
原文:https://www.cnblogs.com/itfenqing/p/10235774.html