• java中的异常处理机制_finally的使用


    finally总结:

      finally代码块:定义一定执行的代码

      通常用于关闭资源或者某些一定执行的代码

    实例1:finally功能演示

    
    
    class FuShuException extends Exception
    {
        FuShuException(String m)
        {
            super(m);
        }
    }
    
    
    class Demo 
    {
        public int div(int x,int y) throws FuShuException
        {
            if(y<0)
            {
                throw new FuShuException("除数为负数");
            }
            return x/y;
        }
    }
    
    
    class ExceptionDemo1
    {
        public static void main(String args[])
        {
            Demo d=new Demo();
            try
            {
                int x=d.div(4,-1);
                System.out.println("x="+x);
            }
            catch(FuShuException e)
            {
                System.out.println(e.toString());
            }
            finally
            {
                System.out.println("finally");        //finally存放的是一定会被执行的代码
            }
            System.out.println("over");
        }
    }
    
    
    
    
    

    运行结果:

    FuShuException: 除数为负数
    finally
    over

    实例2:

     1 class FuShuException extends Exception
     2 {
     3     FuShuException(String m)
     4     {
     5         super(m);
     6     }
     7 }
     8 
     9 
    10 class Demo 
    11 {
    12     public int div(int x,int y) throws FuShuException
    13     {
    14         if(y<0)
    15         {
    16             throw new FuShuException("除数为负数");
    17         }
    18         return x/y;
    19     }
    20 }
    21 
    22 
    23 class ExceptionDemo1
    24 {
    25     public static void main(String args[])
    26     {
    27         Demo d=new Demo();
    28         try
    29         {
    30             int x=d.div(4,-1);
    31             System.out.println("x="+x);
    32         }
    33         catch(FuShuException e)
    34         {
    35             System.out.println(e.toString());
    36             return;
    37         }
    38         finally
    39         {
    40             System.out.println("finally");        //finally存放的是一定会被执行的代码
    41         }
    42         System.out.println("over");
    43     }
    44 }

    运行结果:

    FuShuException: 除数为负数
    finally

  • 相关阅读:
    BZOJ 3033 太鼓达人(DFS+欧拉回路)
    HDU 5121 Just A Mistake
    HDU 5120 Intersection
    HDU 5119 Happy Matt Friends
    HDU 5117 Fluorescent
    BZOJ 1088: [SCOI2005]扫雷Mine
    Codeforces 994 C
    BZOJ 2242: [SDOI2011]计算器
    HDU 4609 3-idiots
    算法笔记--FFT && NTT
  • 原文地址:https://www.cnblogs.com/liangqiyuan/p/5589258.html
Copyright © 2020-2023  润新知