Optional.ofNullable()用法
try-catch-source用法
jdk1.7引入了一个语法叫try-with-resource,它的使用如下:
如果一个类实现了AutoCloseable接口并且重写了close方法,那么这个类就可以写在try后面的括号中,并且能在try-catch块执行后自动执行这个close方法。
举例如下:
public class TryWithResource implements AutoCloseable {
private int age = 18;
@Override
public void close() throws Exception {
System.out.println("this is close 方法");
}
public static void main(String[] args) {
try (TryWithResource tryWithResource = new TryWithResource()) {
System.out.println(tryWithResource.age);
} catch (Exception e) {
e.printStackTrace();
}
}
}
执行这个方法,我们看到打印结果:
18
this is close 方法
很明显这样写和下面这种经典写法的效果是一样的,只是看上去能更加简便一些。
public class TryWithResource{
private int age = 18;
public void close() throws Exception {
System.out.println("this is close 方法");
}
public static void main(String[] args) {
TryWithResource tryWithResource = new TryWithResource();
try {
System.out.println(tryWithResource.age);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
tryWithResource.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
这个经典的写法,是不是很熟悉,java编程中很多对于资源的操作,比如文件流等需要连接的资源,都需要在finally中手动关闭资源,但又怕关闭资源抛异常,所以最终就是finally块中又加了try-catch块,这个结构确实怎么看怎么不得劲,但没办法,JDK1.7之前只能只样写。
但是在JDK1.7后,就可以通过接口的方式,优雅的写这些代码了。
举个例子:
默认的java.io.FileReader等类,已经实现了这个接口了,所以我们在操作文件时,就可以直接用这种优雅的方式来写了,
详见我的另一篇文章:java读文件写文件_zhangSir134的博客-CSDN博客
文章内容如下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-config-service-test.xml")
public class FileTest {
@Test
public void testFile() {
write();
read();
}
/**
* 读
*/
public void read() {
String path = "D:\\file\\myFile.txt";
//Java7的try-with-resources可以优雅关闭文件,异常时自动关闭文件;详细解读https://stackoverflow.com/a/12665271
try (FileReader reader = new FileReader(path);
BufferedReader br = new BufferedReader(reader)
) {
String line;
while ((line = br.readLine()) != null) {
// readLine一行一行读
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 写
*/
public static void write() {
try {
File path = new File("D:\\file\\myFile.txt");
path.createNewFile();
try (FileWriter writer = new FileWriter(path);
BufferedWriter out = new BufferedWriter(writer)
) {
out.write("我写入的内容");
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
1)当try没有捕获到异常且try最后有return语句时:try语句块中的语句逐一被执行(最后的return 语句先不执行),程序将跳过catch语句块,执行finally语句块后继续执行try中的return方法【不要在finally块中使用return方法,否则try中的return不会执行】;
2)当try捕获到异常,catch语句块里没有处理此异常的情况:此异常将会抛给JVM处理,finally语句块里的语句还是会被执行,但finally语句块后的语句不会被执行;
3)当try捕获到异常,catch语句块里有处理此异常的情况:在try语句块中是按照顺序来执行的,当执行到某一条语句出现异常时,程序将跳到catch语句块,并与catch语句块逐一匹配,找到与之对应的处理程序,其他的catch语句块将不会被执行,而try语句块中,出现异常之后的语句也不会被执行,catch语句块执行完后,执行finally语句块里的语句,最后执行finally语句块后的其它语句。