java适当的尝试捕获设计
在Java中实现try/catch时,哪种技术更合适
A:
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();
}
另外,在try/catch块后面跟随一个使用BufferedReader的长代码块是错误的,还是最好在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();
}
# 1 楼答案
正确的技巧可能还包括不捕捉异常,而是允许它们冒泡到调用方。务必使用finally块来清除任何可能会占用资源的状态,但通常最好在父例程中捕获异常,而不是在引发异常的子例程中捕获异常
一般来说,如果在调用例程中知道子例程是否成功会有帮助,那么该子例程不应该捕获其异常,而是应该允许它们向调用方冒泡
# 2 楼答案
当内部try块之后、外部try块之前没有任何事情发生时,B的可读性要高得多。如果要在这两者之间执行逻辑,则必须使用
在第二个示例中,使用finally的第二个版本对于确保无论发生什么(即使函数首先返回)都会调用close至关重要。没有finally的第一个版本实际上是错误的,因为您可能会用尽所有文件句柄,无法打开更多文件
另外,在调用close时,可能需要检查null。如果您使用的是java 7,那么最好使用"try with resources"
# 3 楼答案
对于第一个问题:解决方案增加了不必要的复杂性。使用B或者,如果您使用的是Java 7,请尝试使用以下资源:
对于第二个问题:在第一个版本中,如果
BufferedReader
创建引发异常怎么办?您将使用br
,其后为null,并将抛出NullPointerException。此外,如果发生了其他事情,您将不会调用inFile.close()
,因此您确实需要一个finally
。出于所有这些原因,第二种解决方案同样更好当然,如果您使用的是try with resources(Java7),那么不需要finally块来释放BufferedReader