try - catch - finally
- finally代码区的特点:无论try中的程序是正常执行力,还是出现了异常,最后都一定会执行finally区,除非JVM终止。
- 作用:一般用于在程序执行完成后进行资源的释放操作(专业级做法)。
public class Test {
public static void main(String[] args) throws Exception {
try {
System.out.println(10 / 2);
}catch (Exception e){
e.printStackTrace();
}finally {
System.out.println("===finally执行了一次===");
}
System.out.println(chu(10,2));
}
private static int chu(int a, int b) {
try {
return a / b;
}catch (Exception e){
e.printStackTrace();
return -1; // 代表的是出现异常
}finally {
// 千万不要在finally中返回数据
return 111;
}
}
}
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
InputStream is = null;
OutputStream os = null;
try {
System.out.println(10 / 0);
is = new FileInputStream("D:/tp/123/666.jpg");
os = new FileOutputStream("C:/abc/qwer/666.jpg");
byte[] bytes = new byte[1024];
int len;
while ((len = is.read()) != -1){
os.write(bytes,0,len);
}
System.out.println("复制完成");
} catch (IOException e) {
e.printStackTrace();
} finally {
// 释放资源的操作
try {
if (os != null) os.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (is != null) is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
JDK7开始提供了更简单的资源释放方案:try - with - resource
该资源使用完毕后,会调用其close()方法,完成对资源的释放
- ()中只能放资源,否则报错
- 资源一般指的是最终实现了AutoCloseable接口
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
try(
InputStream is = new FileInputStream("D:/tp/123/666.jpg");
OutputStream os = new FileOutputStream("C:/abc/qwer/666.jpg");
// 注意:这里只能放置资源对象(流对象)
// 资源都是会实现AutoCloseable接口,资源都会有一个close方法
// 用完之后,会自动调用其close方法完成资源的释放操作
) {
byte[] bytes = new byte[1024];
int len;
while ((len = is.read()) != -1){
os.write(bytes,0,len);
}
System.out.println("复制完成");
} catch (IOException e) {
e.printStackTrace();
}
}
}