面向对象之异常—finally

来源:互联网 发布:三菱l系列plc编程手册 编辑:程序博客网 时间:2024/04/25 03:17
 

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 ExceptionDemo5

{

     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");

        

     }

}

 

public void method() throws SQLException

{

     连接数据库

 

     数据操作;//throws new SQLException();

 

     关闭数据库;//该动作,无论是数据造作是否成功,一定要关闭资源。

 

     try

     {

         连接数据库

 

         数据操作;//throws  new SQLException

     }

     catch (SQLException e)

     {

         会对数据库进行异常处理;

         throw new NoException();

     }

         finally

     {

         关闭数据库;

     }

 

}

 

面向对象之异常---处理语句的其他形式

第一种格式

try

{

    

}

catch ()

{

}

第二种格式

try

{

    

}

catch ()

{

}

finally

{}

第三种格式

try

{

    

}

finally

{

}

//记住一点:catch是用于处理异常,如果没哟catch就代表没哟被处理过,如果该异常是检测室的异常,那么必须声明。

class Demo

{

     public void methed()

     {

     throw new Exception()

         {

         try

         {

              throw new Exception();

         }

         /*

         catch (Exception e)

         {

             

              throw e;

         }*/

         finally

              {

              //关资源

              }

    

     }

}

class

public static void main(String[] args)

     {

     System.out.println("")

     }

}

 

面向对象之异常—覆盖是得异常特点

/*

异常在子父类中的体现

1,子类子覆盖时如果父类的方法抛出异常,那么子类的覆盖方法,只能抛出父类的异常或者该异常的子类,

2,如果父类方法抛出多个异常,那么子类的覆盖稚嫩抛出父类的子集

3,如果父类或者接口的方法中没有异常抛出,那么子类在覆盖方法时,也不可以抛出异常

4,如果子类分发生了异常,就必须进行try处理,决不能抛

 

*/

class AException extends Exception

{

}

class BException extends AException

{

}

class CException extends Exception

{

}

/*

  Exception

     |   |--AException

     |        |--BException

     |--CException

 

*/

class Fu

{

     void show() throws AException

     {

 

     }

}

class Test

{

     void function(Fu f)

     {

         tr);

         }

         catch (AException e)

         {

         }

     }

}

 

 

class Zi extends Fu

{

     void show() throws BException

     {

 

     }

}

 

class ArrayText5

{

public static void main(String[] args)

     {

     Test t = new Test();

     t.function(new Fu());

 

     //System.out.println("")

     }

}

原创粉丝点击