try-catch-finally
- 无论try中的程序是正常执行还是异常执行,最后都一定会执行finally
public static void main(String[] args) {
try {
System.out.println(10 / 2);
//return; 跳出方法的执行
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("====finally执行了一次====");
}
System.out.println(chu(10,2));
}
public static int chu(int a,int b){
try {
return a / b;
} catch (Exception e) {
e.printStackTrace();
return -1; //代表出现异常
} finally {
}
}
释放资源的案例
public static void main(String[] args) throws IOException {
InputStream is = null;
OutputStream os = null;
try {
System.out.println(10 / 0);
//需求:复制照片
//1.创建一个字节输入流管道与源文件接通
is = new FileInputStream("D:\\pt\\123.jpg");
//2.创建一个字节输出流管道与目标文件接通
os = new FileOutputStream("C:\\hhh\\123.jpg");
System.out.println(10 / 0);
//3.创建一个字节数组,负责转移字节数据
byte[] buffer = new byte[1024];
//4.从字节输入流读取字节数据,写出去到字节输出流,读多少写出去多少
int len;//记住每次读取了多少个字节
while ((len = is.read(buffer)) != -1){
os.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//释放资源操作
try {
if(is != null) is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(os != null) os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
try-with-resource
- 该资源使用完毕后,会自动调用其close()方法,完成对资源的释放
try(定义资源1;定义资源2;.....) {
可能出现异常的代码;
}catch() { }
public static void main(String[] args) {
try (
//1.创建一个字节输入流管道与源文件接通
InputStream is = new FileInputStream("D:\\pt\\123.jpg");
//2.创建一个字节输出流管道与目标文件接通
OutputStream os = new FileOutputStream("C:\\hhh\\123.jpg");
//注意:这里只能放置资源对象
//什么是资源?资源都是实现AutoCloseable接口。资源都有一个close方法,并且资源放到这里后
//用完之后,会被自动调用其close方法完成资源的释放操作
){
System.out.println(10 / 0);
//3.创建一个字节数组,负责转移字节数据
byte[] buffer = new byte[1024];
//4.从字节输入流读取字节数据,写出去到字节输出流,读多少写出去多少
int len;//记住每次读取了多少个字节
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}