9.7 构造器
9.7 构造器
为异常编写代码时,我们经常要解决的一个问题是
由于前面刚学了
在下面这个例子里,我们创建了一个名为
//: Cleanup.java
// Paying attention to exceptions
// in constructors
import java.io.*;
class InputFile {
private BufferedReader in;
InputFile(String fname) throws Exception {
try {
in =
new BufferedReader(
new FileReader(fname));
// Other code that might throw exceptions
} catch(FileNotFoundException e) {
System.out.println(
"Could not open " + fname);
// Wasn't open, so don't close it
throw e;
} catch(Exception e) {
// All other exceptions must close it
try {
in.close();
} catch(IOException e2) {
System.out.println(
"in.close() unsuccessful");
}
throw e;
} finally {
// Don't close it here!!!
}
}
String getLine() {
String s;
try {
s = in.readLine();
} catch(IOException e) {
System.out.println(
"readLine() unsuccessful");
s = "failed";
}
return s;
}
void cleanup() {
try {
in.close();
} catch(IOException e2) {
System.out.println(
"in.close() unsuccessful");
}
}
}
public class Cleanup {
public static void main(String[] args) {
try {
InputFile in =
new InputFile("Cleanup.java");
String s;
int i = 1;
while((s = in.getLine()) != null)
System.out.println(""+ i++ + ": " + s);
in.cleanup();
} catch(Exception e) {
System.out.println(
"Caught in main, e.printStackTrace()");
e.printStackTrace();
}
}
} ///:~
该例使用了
用于
若
在这个例子中,没有采用前述的标志技术,
String getLine() throws IOException {
return in.readLine();
}
但是当然,调用者现在需要对可能产生的任何
用户使用完毕
⑥:在
在
这个示例也向大家展示了为何在本书的这个地方引入异常的概念。异常与