raises: 在斷言一些代碼塊或者函數時會引發意料之中的異常或者其他失敗的異常,導致程序無法運行時,使用 raises 捕獲匹配到的異常,可以繼續讓代碼正常運行。
可以打印錯誤類型(print(e.type)),錯誤信息(print(e.value.args[0])
def test_04(self): with pytest.raises(Exception) as e: assert 1==2/0 print("打印異常",e,type(e)) print(e.type) print(e.value.args[0]) if "Exception" in str(e): assert 1==1 def test_05(self): assert 1==2/0 print("不打印異常處理")
raise 的異常應該是當前代碼塊最后一行,如果在其后面還有代碼,那么將不會被執行
def test_04(self): with pytest.raises(Exception) as e: assert 1==2/0 print("不被執行打印異常",e,type(e)) #這行不被執行 print("被執行打印異常",e,type(e)) #這行被執行