黑马程序员技术交流社区

标题: 异常_14 [打印本页]

作者: Tauruszzy    时间: 2015-5-10 11:23
标题: 异常_14
  1. class FuShuException extends Exception
  2. {
  3.         FuShuException(String msg)
  4.         {
  5.                 super(msg);
  6.         }
  7. }

  8. class Demo
  9. {
  10.         int div(int a,int b)throws FuShuException
  11.         {
  12.         if(b<0)
  13.                         throw new FuShuException("除数是负数");
  14.                 else
  15.                         return a/b;
  16.         }
  17. }
  18. class  FinallyDemo
  19. {
  20.         public static void main(String[] args)
  21.         {
  22.                 Demo d=new Demo();
  23.                 try
  24.                 {
  25.                         int x=d.div(4,-1);
  26.                         System.out.println("x="+x);
  27.                 }
  28.                 catch (FuShuException e)
  29.                 {
  30.                         System.out.println(e.toString());
  31.                         //return;
  32.                 }
  33.                 finally
  34.                 {
  35.                         System.out.println("一定会执行的语句!");
  36.                 }
  37.                 System.out.println("结尾");
  38.         }
  39. }
复制代码

程序结果:
FuShuException:除数是负数!
一定会执行的语句!
结尾
------------------------------------------------------------------------------------------------------------
  1. class FuShuException extends Exception
  2. {
  3.         FuShuException(String msg)
  4.         {
  5.                 super(msg);
  6.         }
  7. }

  8. class Demo
  9. {
  10.         int div(int a,int b)throws FuShuException
  11.         {
  12.         if(b<0)
  13.                         throw new FuShuException("除数是负数");
  14.                 else
  15.                         return a/b;
  16.         }
  17. }
  18. class  FinallyDemo
  19. {
  20.         public static void main(String[] args)
  21.         {
  22.                 Demo d=new Demo();
  23.                 try
  24.                 {
  25.                         int x=d.div(4,-1);
  26.                         System.out.println("x="+x);
  27.                 }
  28.                 catch (FuShuException e)
  29.                 {
  30.                         System.out.println(e.toString());
  31.                         return;//主程序在此结束
  32.                 }
  33.                 finally
  34.                 {
  35.                         System.out.println("一定会执行的语句!");
  36.                 }
  37.                 System.out.println("结尾");
  38.         }
  39. }
复制代码

程序结果:
FuShuException:除数是负数!
一定会执行的语句!
---------------------------------------------------------------
总结:finally代码库定义一定执行的语句,通常用于关闭资源。比如连接数据库操作数据时,当操作完或者发生错误突然连接失败时,都要给出断开数据库操作,因为数据库运行在主机之上,而主机的资源有限,导致数据库的连接数有限,如果都连接不断开,当达到最大连接数时,别的人是没有办法再连接的。finally就可以解决类似的问题。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2