/*
 finally代码块:定义一定执行的代码,
 通常用于关闭资源,

*/

 

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("出现除数为负数!");
  }
  return a/b;
 }
}

class ExceptionDemo4
{
 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 ;//结束主函数,ruturn之后,finally执行,下面的System.out.println("Over");//不执行
  }
  finally
  {
   System.out.println("finally");//finally中存放的是一定会被执行的代码
  }
  
  System.out.println("Over");
 }
}

 


/*

 
 

public void method()throws NoException
{
 连接数据库;
 
 数据库操作;//可能会出问题:throw new SQLException();然后整个函数结束!
 
 关闭数据库;//这操作,无论数据操作是否成功,一定要关闭资源


 
 //面试!!!!!!一定要关闭数据库(资源)-----【使用完资源要释放】
 try
 {
  连接数据库;
  
  数据库操作;//throw new SQLException();
 }
 catch (SQLException e)
 {
  会对数据库进行异常处理;//问题封装!
  throw new NoException();//对外暴漏一下!//必须有
 }
 finally//重点掌握!
 {
  关闭数据库;
 }

}


*/

 

 

 

posted on 2013-03-12 23:47  Stone_S123  阅读(105)  评论(0编辑  收藏  举报