try: ... except Exception1: ... except Exception2: ... finally: ...
若是在try中發生錯誤,那麼except將捕獲到指定錯誤,而後執行該段語句;而不管有無錯誤finally都會執行.python
#-*-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
示例:this
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直接運行單元測試,這樣能夠一次運行多個單元測試spa
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()