《On Java 8》中文版,又名《Java编程思想》 第5版
接下来的都是个人学习过程的笔记,不是总结,没有参考价值,但是这本书很棒
Try-With-Resources 用法
这一章我只看了这一节= =
// exceptions/MessyExceptions.java
import java.io.*;
public class MessyExceptions {
public static void main(String[] args) {
InputStream in = null;
try {
in = new FileInputStream(
new File("MessyExceptions.java"));
int contents = in.read();
// Process contents
} catch(IOException e) {
// Handle the error
} finally {
if(in != null) {
try {
in.close();
} catch(IOException e) {
// Handle the close() error
}
}
}
}
}
如上所示,IO需要处理一大堆异常
// exceptions/StreamsAreAutoCloseable.java
import java.io.*;
import java.nio.file.*;
import java.util.stream.*;
public class StreamsAreAutoCloseable {
public static void
main(String[] args) throws IOException{
try(
Stream<String> in = Files.lines(
Paths.get("StreamsAreAutoCloseable.java"));
PrintWriter outfile = new PrintWriter(
"Results.txt"); // [1]
) {
in.skip(5)
.limit(1)
.map(String::toLowerCase)
.forEachOrdered(outfile::println);
} // [2]
}
}
括号内的部分称为资源规范头(resource specification header),资源规范头里的对象必须实现AutoCloseable
揭示细节
// exceptions/AutoCloseableDetails.java
class Reporter implements AutoCloseable {
String name = getClass().getSimpleName();
Reporter() {
System.out.println("Creating " + name);
}
public void close() {
System.out.println("Closing " + name);
}
}
class First extends Reporter {}
class Second extends Reporter {}
public class AutoCloseableDetails {
public static void main(String[] args) {
try(
First f = new First();
Second s = new Second()
) {
}
}
}
按创建顺序相反的顺序关闭
// exceptions/BodyException.java
class Third extends Reporter {}
public class BodyException {
public static void main(String[] args) {
try(
First f = new First();
Second s2 = new Second()
) {
System.out.println("In body");
Third t = new Third();
new SecondExcept();
System.out.println("End of body");
} catch(CE e) {
System.out.println("Caught: " + e);
}
}
}
t
对象永远不会被close掉,因为他没在资源头里创建
// exceptions/CloseExceptions.java
class CloseException extends Exception {}
class Reporter2 implements AutoCloseable {
String name = getClass().getSimpleName();
Reporter2() {
System.out.println("Creating " + name);
}
public void close() throws CloseException {
System.out.println("Closing " + name);
}
}
class Closer extends Reporter2 {
@Override
public void close() throws CloseException {
super.close();
throw new CloseException();
}
}
public class CloseExceptions {
public static void main(String[] args) {
try(
First f = new First();
Closer c = new Closer();
Second s = new Second()
) {
System.out.println("In body");
} catch(CloseException e) {
System.out.println("Caught: " + e);
}
}
}
注意,资源头里对象c
创建的时候是不会抛出异常的,catch(CloseException e)
捕获的是在其关闭时可能抛出的异常。
另外,子类重写方法抛出的异常必须小于父类方法所抛出的异常,或者不抛出异常。
1,子类重写父类方法要抛出与父类一致的异常,或者不抛出异常
2,子类重写父类方法所抛出的异常不能超过父类的范畴