try关键字后可以定义finally代码块,finally块中定义的代码,总在try和任何catch块后,方法完成之前运行
正常情况下,不管是否抛出或者捕获异常,finally都会执行
简单的例子
try {
System.out.println("The count is " + Integer.parseInt(count));
} catch (NumberFormatException e) {
System.out.println("No count");
} finally {
System.out.println("In finally");
}
这个实例中不管参数的值是多少,是否正确,都一定会输出In finally
无异常
try {
System.out.println("Inside try");
} finally {
System.out.println("Inside finally");
}
程序可以正常执行,没有异常发生,输出结果为
Inside try
Inside finally
有异常但是没处理
try {
System.out.println("Inside try");
throw new Exception(); //手动抛出一场
} finally {
System.out.println("Inside finally");
}
虽然抛出异常没有处理,JVM依然会执行finallu代码块中的代码
Inside try
Inside finally
Exception in thread "main" java.lang.Exception
try代码块中带返回值
public class Main {
static String test(){
try {
System.out.println("try");
return "213";
}finally {
System.out.println("finally"); //如果不注释,IDEA会自动标红,无法运行
}
System.out.println("123");
}
public static void main(String[] args) {
// write your code here
System.out.println(test());
}
}
输出结果为
try
finally
213
在catch中返回
public class Main {
static String test(){
try {
System.out.println("try");
throw new Exception();
}catch (Exception e){
System.out.println("catch");
return "213";
} finally {
System.out.println("finally");
}
}
public static void main(String[] args) {
// write your code here
System.out.println(test());
}
}
输出结果为
try
catch
finally
213
什么时候finally不执行
- 调用System.exit函数
public static void main(String[] args) {
// write your code her
try {
System.exit(1);
} finally {
System.out.println("123");
}
}
这样就不会执行,123
也不会输出
- 调用halt函数
public class Main {
public static void main(String[] args) {
// write your code her
try {
Runtime.getRuntime().halt(1);
} finally {
System.out.println("123");
}
}
}
也不会执行
- 守护线程
- try代码块中无限循环
finally中包含返回语句会造成的问题
- 忽视异常
package com.company;
public class Main {
static String test(){
try {
System.out.println("123");
throw new Exception(); //未处理异常
} finally {
System.out.println("finally");
}
}
public static void main(String[] args) {
// write your code her
System.out.println(test());
}
}
正常情况下会抛出异常
但是通过finally语句return后就不会抛出异常
public class Main {
static String test(){
try {
System.out.println("123");
throw new Exception();
} finally {
return "finally";
}
}
public static void main(String[] args) {
// write your code her
System.out.println(test());
}
}
程序正常运行,并输出
123
finally
- 覆盖其他返回语句
public class Main {
static String test(){
try {
System.out.println("123");
return "try"; //被覆盖
} finally {
return "finally";
}
}
public static void main(String[] args) {
// write your code her
System.out.println(test());
}
}
输出结果为
123
finally
- 改变throw或return行为
public class Main {
static String test(){
try {
System.out.println("123");
return "try";
} finally {
throw new Exception();
}
}
public static void main(String[] args) {
// write your code her
System.out.println(test());
}
}
上面程序try中没有异常,可以正常返回,但是在finally中抛出了异常,就会导致程序无法正常执行