亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

處理傳播錯誤

處理傳播錯誤

當年話下 2023-10-31 21:27:17
在我的代碼中,我有一個主函數,它調用一個從文件中讀取一些數據并返回該數據的函數,然后以不同的方式使用該數據。顯然存在用戶輸入無法找到的文件名從而導致錯誤的風險。我想捕獲此錯誤并輸出我編寫的錯誤消息,而無需回溯等。我嘗試使用標準的 try- except 語句,該語句幾乎按預期工作,除了現在未讀取數據,因此當我嘗試時出現新錯誤使用空變量進行計算。在異常塊中使用sys.exitorraise SystemExit會導致在控制臺中寫入帶有回溯的錯誤,并且捕獲第一個錯誤的整個點感覺是多余的。我可以將整個程序包裝在一個 try 語句中,但我從未見過這樣做,而且感覺不對。如何以干凈的方式終止程序或隱藏所有后續錯誤? def getData(fileName):        try:            file = open(fileName,"r")            data = file.readlines()            file.close()            x = []            y = []            for i in data:                noNewline = i.rstrip('\n')                x.append(float(noNewline.split("\t")[0]))                y.append(float(noNewline.split("\t")[1]))            return x,y        except FileNotFoundError:            print("Some error messages")    def main(fileName):        x,y = getData(fileName)        # diffrent calculations with x and y
查看完整描述

3 回答

?
慕桂英4014372

TA貢獻1871條經驗 獲得超13個贊

因為main是一個函數,你可能return會出錯:


def main(filename):

    try:

        x, y = getData(filename)

    except FileNotFoundError:

        print("file not found")

        return


    # calculations here


查看完整回答
反對 回復 2023-10-31
?
FFIVE

TA貢獻1797條經驗 獲得超6個贊

以下


def getData(fileName):

    file = open(fileName,"r")

    data = file.readlines()

    file.close()

    x = []

    y = []

    for i in data:

        noNewline = i.rstrip('\n')

        x.append(float(noNewline.split("\t")[0]))

        y.append(float(noNewline.split("\t")[1]))

    return x,y



def main(fileName):

    # if you only want to handle exception coming from 'getData'

    try:

        x,y = getData(fileName)

    except Exception as e:

        print(f'could not get data using file {filename}. Reason: {str(e)}')

        return

    # do something with x,y

if __name__ == "__main__":

    main('get_the_file_name_from_somewhere.txt')


查看完整回答
反對 回復 2023-10-31
?
慕尼黑的夜晚無繁華

TA貢獻1864條經驗 獲得超6個贊

解決方案

sys.exitSystemExit采用可選參數 - 0 被視為成功終止。

例子

sys.exit(0)
raise SystemExit(0)

參考

Python sys.exit:https://docs.python.org/3/library/sys.html#sys.exit


查看完整回答
反對 回復 2023-10-31
  • 3 回答
  • 0 關注
  • 167 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號