python異常捕捉處理

xiaofeiyuan發表於2020-09-26

python異常捕捉處理

python異常處理相關需求,後續待補充。

一,try…except…捕捉異常

  1. 獲取異常並定位出錯誤的程式碼是哪一行,通過traceback模組可定位出錯程式碼的行數與錯誤資訊
import traceback
import time


def func():
    try:
        assert 1 / 0
    except Exception as e:
        print('func %s' % str(e))


def func2():
    try:
        assert 1 / 0
    except Exception as e:
        error_detail = traceback.format_exc()
        print('func2 %s' % error_detail)
        print('*' * 50)
        time.sleep(0.1)
        traceback.print_exc()


func()
print('*' * 50)
time.sleep(0.1)
func2()

執行結果

func division by zero
**************************************************
func2 Traceback (most recent call last):
  File "D:/Program Files/RPA-Project/Learning/test.py", line 14, in func2
    assert 1 / 0
ZeroDivisionError: division by zero

**************************************************
Traceback (most recent call last):
  File "D:/Program Files/RPA-Project/Learning/test.py", line 14, in func2
    assert 1 / 0
ZeroDivisionError: division by zero