zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    WP8日历(含农历)APP
    NHibernate3剖析:Mapping篇之集合映射基础(2):Bag映射
    初探springmvc
    树的子结构
    Java内存分析
    java8_api_misc
    iOS开发多线程篇 09 —NSOperation简单介绍
    CALayer1-简介
    NSCharacterSet
    iOS 音频开发
  • 原文地址:https://www.cnblogs.com/fxyfirst/p/3810942.html
Copyright © 2011-2022 走看看