3 回答

TA貢獻1871條經驗 獲得超13個贊
因為main是一個函數,你可能return會出錯:
def main(filename):
try:
x, y = getData(filename)
except FileNotFoundError:
print("file not found")
return
# calculations here

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')

TA貢獻1864條經驗 獲得超6個贊
解決方案
sys.exit
并SystemExit
采用可選參數 - 0 被視為成功終止。
例子
sys.exit(0) raise SystemExit(0)
參考
Python sys.exit:https://docs.python.org/3/library/sys.html#sys.exit
添加回答
舉報