程序不被中断(JVM进程直接死掉)的情况,总是执行的
没有返回值的情况
/**
* 没有返回值的情况下
*/
public static void method1() {
try {
int i = 1 / 0;
} catch (Exception e) {
e.printStackTrace();
System.out.println("catch");
}finally {
System.out.println("finally");
}
}
//输出结果
java.lang.ArithmeticException: / by zero
at com.dyy.FinallyDemo.method1(FinallyDemo.java:13)
at com.dyy.FinallyDemo.main(FinallyDemo.java:6)
catch
finally
有返回值的情况下
return在外层
/**
* 有返回值的情况下 return在外层
*/
public static int method2() {
int k = 0;
try {
int i = 1 / 0;
} catch (Exception e) {
e.printStackTrace();
System.out.println("catch");
}finally {
System.out.println("finally");
k = 1 ;
}
return k;
}
//输出
java.lang.ArithmeticException: / by zero
at com.dyy.FinallyDemo.method2(FinallyDemo.java:28)
at com.dyy.FinallyDemo.main(FinallyDemo.java:6)
catch
finally
1
return在内层
/**
* 没有返回值的情况下 return在内层
*/
public static int method3() {
int k = 0;
try {
++k;
int i = 1 / 0;
++k;
return k;
} catch (Exception e) {
e.printStackTrace();
++k;
System.out.println("catch");
}finally {
++k;
System.out.println("finally");
}
return k;
}
//输出结果
java.lang.ArithmeticException: / by zero
at com.dyy.FinallyDemo.method3(FinallyDemo.java:46)
at com.dyy.FinallyDemo.main(FinallyDemo.java:6)
catch
finally
3
说明finally总是会执行的
使用场景
锁资源释放
public void put(Object object) throws InterruptedException {
final ReentrantLock lock = this.lock;
//获取独占锁 可中断的
lock.lockInterruptibly();
try {
//具体对共享资源的操作
} finally {
//释放独占锁
lock.unlock();
}
}
流资源的处理
public static void method4(){
File file = new File("/xx");
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[1024];
StringBuilder sb = new StringBuilder();
while (fileInputStream.read(bytes) != -1) {
sb.append(new String(bytes));
}
System.out.println("result=" + sb.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fileInputStream != null){
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
连接的释放
public static void metohd5(){
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("xxx:3306","username","password");
//具体操作
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(connection != null){
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
总结
对一些有限的资源,我们在使用完毕之后一定要记得关闭掉,避免都资源造成浪费,对于一些经常会使用到的资源,我们总是需要打开使用然后关闭,也就有了池的概念,把一些资源放入池中,不关闭掉,使用的时候可以直接获取,使用完之后放回池中就可以了。