- class FuShuException extends Exception
- {
- FuShuException(String msg)
- {
- super(msg);
- }
- }
- class Demo
- {
- int div(int a,int b)throws FuShuException
- {
- if(b<0)
- throw new FuShuException("除数是负数");
- else
- return a/b;
- }
- }
- class FinallyDemo
- {
- 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());
- //return;
- }
- finally
- {
- System.out.println("一定会执行的语句!");
- }
- System.out.println("结尾");
- }
- }
复制代码
程序结果:
FuShuException:除数是负数!
一定会执行的语句!
结尾
------------------------------------------------------------------------------------------------------------
- class FuShuException extends Exception
- {
- FuShuException(String msg)
- {
- super(msg);
- }
- }
- class Demo
- {
- int div(int a,int b)throws FuShuException
- {
- if(b<0)
- throw new FuShuException("除数是负数");
- else
- return a/b;
- }
- }
- class FinallyDemo
- {
- 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());
- return;//主程序在此结束
- }
- finally
- {
- System.out.println("一定会执行的语句!");
- }
- System.out.println("结尾");
- }
- }
复制代码
程序结果:
FuShuException:除数是负数!
一定会执行的语句!
---------------------------------------------------------------
总结:finally代码库定义一定执行的语句,通常用于关闭资源。比如连接数据库操作数据时,当操作完或者发生错误突然连接失败时,都要给出断开数据库操作,因为数据库运行在主机之上,而主机的资源有限,导致数据库的连接数有限,如果都连接不断开,当达到最大连接数时,别的人是没有办法再连接的。finally就可以解决类似的问题。 |
|