第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

處理傳播錯誤

處理傳播錯誤

當(dāng)年話下 2023-10-31 21:27:17
在我的代碼中,我有一個主函數(shù),它調(diào)用一個從文件中讀取一些數(shù)據(jù)并返回該數(shù)據(jù)的函數(shù),然后以不同的方式使用該數(shù)據(jù)。顯然存在用戶輸入無法找到的文件名從而導(dǎo)致錯誤的風(fēng)險。我想捕獲此錯誤并輸出我編寫的錯誤消息,而無需回溯等。我嘗試使用標(biāo)準(zhǔn)的 try- except 語句,該語句幾乎按預(yù)期工作,除了現(xiàn)在未讀取數(shù)據(jù),因此當(dāng)我嘗試時出現(xiàn)新錯誤使用空變量進行計算。在異常塊中使用sys.exitorraise SystemExit會導(dǎo)致在控制臺中寫入帶有回溯的錯誤,并且捕獲第一個錯誤的整個點感覺是多余的。我可以將整個程序包裝在一個 try 語句中,但我從未見過這樣做,而且感覺不對。如何以干凈的方式終止程序或隱藏所有后續(xù)錯誤? 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條經(jīng)驗 獲得超13個贊

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


def main(filename):

    try:

        x, y = getData(filename)

    except FileNotFoundError:

        print("file not found")

        return


    # calculations here


查看完整回答
反對 回復(fù) 2023-10-31
?
FFIVE

TA貢獻1797條經(jīng)驗 獲得超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')


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

TA貢獻1864條經(jīng)驗 獲得超6個贊

解決方案

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

例子

sys.exit(0)
raise SystemExit(0)

參考

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


查看完整回答
反對 回復(fù) 2023-10-31
  • 3 回答
  • 0 關(guān)注
  • 172 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號