這將被認爲是更合適的技術來實現Java中的try/catch語句:正確的嘗試捕捉設計
答:
Date lastMod = null;
BufferedReader inFile = null;
try {
inFile = new BufferedReader(new FileReader("C:\\Java\\settings.ini"));
try {
lastMod = new Date(Long.parseLong(inFile.readLine()));
} catch (IOException e) {
e.printStackTrace();
}
} catch(FileNotFoundException e) {
e.printStackTrace();
}
或B:
Date lastMod = null;
BufferedReader inFile = null;
try {
inFile = new BufferedReader(new FileReader("C:\\Java\\settings.ini"));
lastMod = new Date(Long.parseLong(inFile.readLine()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
此外,有使用BufferedReader的一長段代碼跟隨try/catch塊是錯誤的,還是傾向於在try/catch中包含很長的代碼塊?
例如:
public static void main(String[] args) {
Date lastMod = null;
BufferedReader inFile = null;
try {
inFile = new BufferedReader(new FileReader("C:\\Java\\settings.ini"));
lastMod = new Date(Long.parseLong(inFile.readLine()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Long block of code using inFile
inFile.readLine();
inFile.close();
對戰:
public static void main(String[] args) {
Date lastMod = null;
BufferedReader inFile = null;
try {
inFile = new BufferedReader(new FileReader("C:\\Java\\settings.ini"));
lastMod = new Date(Long.parseLong(inFile.readLine()));
//Long block of code using inFile
inFile.readLine();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
inFile.close();
}
B.它更簡潔可讀.... – Thihara 2013-03-08 04:21:49
你有沒有聽說過或嘗試過「試用資源」? – Abubakkar 2013-03-08 04:23:34
兩種情況下,選項'B'! – SudoRahul 2013-03-08 04:23:51