(38)finally和堆catch的理解

来源:互联网 发布:水电上门维修软件 编辑:程序博客网 时间:2024/06/05 05:33

一、finally引入:


public void method(){

                  连接数据库;

                  数据操作;//可能操作出现错误如删除不存在的东西,添加信息格式不正确等,该动作,无论数据操作是否成功,一定要关闭数据库

                  关闭数据库;

         }

正确写法:

public void method ()throws   SQLException

      {

                 try

              {

                连接数据库;

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

              }

               catch(SQLException  e)

             {

                   会对数据库进行异常处理

                     throw new NoException();

             }

             finally

            {

               关闭数据库

             }

class NoException  extends Exception

            {

             }

二、finally代码块:定义一定会执行的代码

        通常是关闭资源的

三、try,catch语句的三种格式

     ①try{}

       catch{}

      ②try{}

       catch{}

       finally{}

     ③try{}

       finally{}

四、举个例子


 public void method(){           /*throw new Exception();若方法内抛出异常,可以有两种解决方式①trycatch自己解决,就不用再声明了            *   ②方法内不处理,则必须在方法上声明            */      try {   throw new Exception();         }   catch(Exception e) //只要写catch就相当于处理异常了,编译就能通过,相当于问题在内部解决了,外面不用知道发生什么事了   {   //throw e;还是和throw new Exception();一样的问题,要么自己内部解决,要么函数上声明   try {throw e;        }                   catch (Exception e1) {       }      }   }



        try {   throw new Exception();           }      finally {        //关资源    }这样写不正确,方法内抛出异常,没有解决,所以编译不会通过


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




阅读全文
0 0