• Java-- 异常之使用finally进行清理


      对于一些代码,可能会希望无论try块中的异常是否抛出,它们都能得到执行。这通常适用于内存回收之外的情况。为了达到这样的效果,可以在异常处理程序后面加上finally子句。如下:

     1 try{
     2 
     3   //The guarded region: Dangerous activities
     4 
     5   //taht might throw A,B, or C
     6 
     7 }catch(A a1){
     8 
     9   //handler for situation A
    10 
    11 }catch(B b1){
    12 
    13   //Handler for situation B
    14 
    15 }catch(C c1){
    16 
    17   //Handler for situtation C
    18 
    19 }finally{
    20 
    21   //activities that happen every time
    22 
    23 }

    为了证明finally总能运行,可以试试如下程序:
     1 package com.exceptions;
     2 
     3 class ThreeException extends Exception{}
     4 public class FinallyWorks {
     5     static int count = 0;
     6     public static void main(String[] args){
     7         while(true){
     8             try{
     9                 if(count++ ==0)
    10                     throw new ThreeException();
    11                 System.out.println("No Exception");
    12             }catch(ThreeException e){
    13                 System.out.println("ThreeException");
    14             }finally{
    15                 System.out.println("In finally clause");
    16                 if(count == 2) break;
    17             }
    18         }
    19     }
    20 }

    结果如下:

    1 ThreeException
    2 In finally clause
    3 No Exception
    4 In finally clause
  • 相关阅读:
    网络流(平面图转对偶图)
    666
    期望总结
    docker-1-简介
    22、整合mybatis
    21、整合Druid数据源
    20、Springboot 与数据访问(JDBC/自动配置)
    19、配置嵌入式servlet容器(下)
    18、配置嵌入式servlet容器(2)
    17、配置嵌入式servlet容器(1)
  • 原文地址:https://www.cnblogs.com/fxyfirst/p/3810942.html
Copyright © 2020-2023  润新知