java中的finally语句块
1、使用:
try{
}catch(){
}finally{
}
try{
}finally{
}
2、finally中的代码一定会执行,只有在已执行System.exit(0)退出JVM这一种情况下不会被执行
3、
public class Example {
public static void main(String[] args) {
try{
System.out.println("abc");
return;
}finally{
System.out.println("hhh");
}
}
}
执行结果:
虽然try语句块中有return语句,但是先执行System.out.println(“abc”);再执行finally语句块再执行return
4、
public class Example {
public static void main(String[] args) {
try{
FileInputStream fileInputStream=new FileInputStream("Test.java");//Test.java并不存在
System.out.println("heihei");
}catch(Exception e){
e.printStackTrace();
}finally{
System.out.println("hhh");
}
}
}
运行结果:
try…catch()…只能保证编译通过,由于Test.java不存在因此还是会发生运行时异常,e.printStackTrace()输出了异常栈信息,发生异常就不会再继续往下执行System.out.println(“heihei”);但是还是会执行finally语句块输出hhh
5、
public class Example {
public static void main(String[] args) {
try{
System.exit(0);
System.out.println("heihei");
}finally{
System.out.println("hhh");
}
}
}
运行结果:
在执行finally语句块之前已经退出了JVM,不再执行其他代码,也不再执行finally语句块
7、
public class Example {
public static void main(String[] args) {
m1();
}
public static void m1(){
try{
int i=10;
}finally{
i++;
System.out.println(i);
}
}
}
运行结果:
i是在try语句块中声明的,其作用域只在try语句块内,在finally语句块中无法访问 i
8、
public class Example {
public static void main(String[] args) {
int m=m1();
System.out.println("heihei"+m);
}
public static int m1(){
int i=10;
try{
return i;
}finally{
i++;
System.out.println("hh"+i);
}
}
}
运行结果:
值得注意的是finally语句块中对i进行的操作并未对return的 i 起作用
原因是代码的执行原理其实是
public class Example {
public static void main(String[] args) {
int m=m1();
System.out.println("heihei"+m);
}
public static int m1(){
int i=10;//放在外面,便于finally语句块访问
try{
int temp=i;
return temp;
}finally{
i++;
System.out.println("hh"+i);
}
}
}
JVM将 i 变量临时赋给一个temp变量,把temp变量返回了,把 i 变量加一了
说白了就是try会将变量的值临时储存起来,然后返回这个储存的值
还需要注意的是程序的执行顺序,程序先执行了finally语句,然后才执行return语句
9、由于finally语句块中的代码一定被执行,为了保证某资源一定被释放,通常在finally语句块中释放资源
public class Example {
public static void main(String[] args) {
FileInputStream fileInputStream=null;//便于finally语句块访问
try{
fileInputStream =new FileInputStream("F:/workspace/hello/src/hello/Hello.java");//Hello.java真实存在
}catch(FileNotFoundException e){
e.printStackTrace();
}finally//为了保证资源释放
{
//fileInputStream.close();//流是一个资源,用完时需要关闭
//由于close方法的声明抛出异常,因此使用close方法时要处理异常
//public void close() throws IOException{}
if(fileInputStream!=null)//防止空指针异常
{
try{
fileInputStream.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
}
}
运行结果:
找到了文件并且最后关闭了输入流
10、
final:关键字
finalize:Object类内方法
finally:语句块 异常处理机制中 通常用于释放资源
11、当try语句块中发生异常时,交给catch处理异常,catch处理完整个try{…}catch(…){…}结构就执行结束了,因此不会执行try语句块中的后续代码,但会继续执行try{…}catch(…){…}这个结构后面跟的代码
public class Hello {
public static void main(String[] args) {
try{
FileInputStream fileInputStream=new FileInputStream("hhh.txt");//hhh.txt并不存在
System.out.println("hahaha");
}catch(FileNotFoundException e){
e.printStackTrace();
}
System.out.println("heihei");
}
}
运行结果:
虽然发生了异常,但也输出了heihei