finally 块
一、使用前提
finally块的使用前提是必须要存在try块才能使用。
class Main {
public static void main(String[] args)
{
div(4,0);
}
public static void div(int a, int b){
try{
int c = a/b;
System.out.println("c = " + c);
}catch(Exception e){
String message = e.getMessage();
System.out.println(message);
}finally{
System.out.println("程序运行结束");
}
}
}
二、执行情况
finally块的代码在任何情况下都会执行的,除了jvm退出的情况。
1.没有出现异常
class Main {
public static void main(String[] args)
{
div(4,2); //除数非0
}
public static void div(int a, int b){
try{
int c = a/b;
System.out.println("c = " + c);
}catch(Exception e){
String message = e.getMessage();
System.out.println(message);
}finally{
System.out.println("程序运行结束");
}
}
}
2.出现异常
class Main {
public static void main(String[] args)
{
div(4,0);
}
public static void div(int a, int b){
try{
int c = a/b;
System.out.println("c = " + c);
}catch(Exception e){
String message = e.getMessage();
System.out.println(message);
}finally{
System.out.println("程序运行结束");
}
}
}
3.catch块抛出异常后
class Main {
public static void main(String[] args)
{
div(4,0);
}
public static void div(int a, int b){
try{
int c = a/b;
System.out.println("c = " + c);
}catch(Exception e){
String message = e.getMessage();
System.out.println(message);
throw e; //抛出异常
}finally{
System.out.println("程序运行结束");
}
}
}
4.try块return后
class Main {
public static void main(String[] args)
{
div(4,0);
}
public static void div(int a, int b){
try{
if(b==0){
return;
}
int c = a/b;
System.out.println("c = " + c);
}catch(Exception e){
String message = e.getMessage();
System.out.println(message);
}finally{
System.out.println("程序运行结束");
}
}
}
注意:jvm退出的情况
class Main {
public static void main(String[] args)
{
div(4,0);
}
public static void div(int a, int b){
try{
if(b==0){
System.exit(0);//退出jvm
}
int c = a/b;
System.out.println("c = " + c);
}catch(Exception e){
String message = e.getMessage();
System.out.println(message);
}finally{
System.out.println("程序运行结束");
}
}
}
三、使用场景
finally非常适合做资源释放的工作,这样子可以保证资源文件在任何情况下都会被释放。
import java.io.*;
class Main {
public static void main(String[] args) {
FileReader fileReader = null;
try{
//找到目标文件
File file = new File("d:\\ReadandWrite.txt");
//建立程序与文件的数据通道
fileReader = new FileReader(file);
//读取文件
char[] buf = new char[1024];
int length = 0;
length = fileReader.read(buf);
System.out.println("读取到的内容:"+ new String(buf,0,length));
}catch(IOException e){
System.out.println("读取资源文件失败....");
}finally{
try{
//关闭资源
fileReader.close();
System.out.println("释放资源文件成功....");
}catch(IOException e){
System.out.println("释放资源文件失败....");
}
}
}
}
四、与try块的三种组合方式
第一种: 比较适用于有异常要处理,但是没有资源要释放的。
扫描二维码关注公众号,回复:
1549659 查看本文章
try{
可能发生异常的代码
}catch(捕获的异常类型 变量名){
处理异常的代码
}
第二种:比较适用于既有异常要处理又要释放资源的代码。
try{
可能发生异常的代码
}catch(捕获的异常类型 变量名){
处理异常的代码
}finally{
释放资源的代码;
}
第三种: 比较适用于内部抛出的是运行时异常,并且有资源要被释放。
try{
可能发生异常的代码
}finally{
释放资源的代码;
}