iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 24
0
Software Development

從零開始的Python練成記系列 第 24

[Day 24]程式碼出差錯?用Try/Except

有些時候,在執行程式碼可能會出現異常狀況,就像是輸入的值沒有辦法進行轉換的時候,就會使程式直接崩潰;那如果要處理這種狀況的時候,大多數都是先以設計一連串的if/elif/else來處理,可是這種邏輯就會變得相當繁雜,所以今天就要來說明一下try/except的用途
其實,在Java裡面也有這種機制,但是稱為try/catch,就先來看看用法吧:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Check {
	public static void main(String[] args){
		Main m = new Main();
		FileReader fr;
		try {
            //因為上面有使用FileReader,所以就要處理例外情形(也就是沒有讀到檔案的狀況)
			fr = new FileReader("menu.txt");
			BufferedReader in = new BufferedReader(fr);
			String line = in.readLine();
			while(line!=null){
				try{
					String[] token = line.split(",");
					int id = Integer.parseInt(token[0]);
					String name = token[1];
					int cost = Integer.parseInt(token[2]);
					int kcal = Integer.parseInt(token[3]);
					m.dishes.add(new Dish(id,name,cost,kcal));
				}catch(NumberFormatException e){
					e.printStackTrace();
				}
				line = in.readLine();
			}
			m.on();
		} catch (FileNotFoundException e) {
            //當Try的內容失敗,就會引導到下方的catch做後續的動作,但是catch這邊還要再設定條件,
            //否則會先因為沒有對應的catch條件而程式崩潰
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}
//上方程式碼來自我自己的Github專案

接下來,就來對比一下在Python裡面的try/except

try:
    print(my_text)
    #在這個程式,我並沒有宣告有關my_text這個變數,所以就會使程式崩潰
except NameError:
    #所以在這裡的except就要對這例外情形的設定處理方式
    print("The target was not found!")
"""
程式會先因為沒有"my_text"這個變數而先導出NameError,所以在except的地方就指定「如果出現NameError的時候」要讓程式有個回應,最後就會印出"The target was not found!",讓程式自動結束,而不是讓整個程式自生自滅
"""

老實說,越是接近尾聲,越來越沒靈感了


上一篇
[Day 23]真正精采的要來了:把DataFrame型式轉出到txt檔
下一篇
[Day 25]感覺又是新的開始:GUI介面開發
系列文
從零開始的Python練成記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言