錯誤堆棧信息記錄錯誤日志


前言

任何代碼執行前都需要考慮代碼bug,當出現錯誤信息時需要展示其錯誤信息

通過try 方式

代碼一

def f1():
    result = 123
    int('asdf')                 #故意設置一個錯誤的代碼源
    return result

def run():
    try:
        ret = f1()
        print(ret)
    except Exception as e:
        print(e)     
run()
View Code

錯誤信息

invalid literal for int() with base 10: 'asdf'

Process finished with exit code 0
View Code

在try 基礎上引入traceback

代碼二

import traceback


def f1():
    result = 123
    int('asdf')                 #故意設置一個錯誤的代碼源
    return result

def run():
    try:
        ret = f1()
        print(ret)
    except Exception as e:
        print(traceback.format_exc())
run()
View Code

錯誤信息

Traceback (most recent call last):
  File "E:/cmdb/auto_client_fang/test.py", line 12, in run
    ret = f1()
  File "E:/cmdb/auto_client_fang/test.py", line 7, in f1
    int('asdf')                 #故意設置一個錯誤的代碼源
ValueError: invalid literal for int() with base 10: 'asdf'

注:不僅提示錯誤類型,還提供錯誤的代碼位置
View Code

總結

python 代碼從上而下執行,有一行出錯則代碼執行中斷,py文件退出狀態為異常1。當設置try 后即使出現錯誤請況,后面代碼還會執行,錯誤代碼可以正常打印出來,退出狀態為正常的0。

引入 traceback 后錯誤的信息提供的更詳細,且錯誤信息為字符串可以直接存入變量以便寫入錯誤日志。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM