java 异常三

来源:互联网 发布:java中getField 编辑:程序博客网 时间:2024/06/06 16:37
在异常中,finally代码块中的代码是一定可以执行到的。无论出没出现异常都一定会执行finally代码块中代码。
finally重要作用的举例:
与数据库进行数据交互的过程:
1,连接数据库;
2,操作数据;
3,断开与数据库的连接;此需求可以在finally代码块中实现。
//关闭数据库是非常重要的,因为数据库服务器可提供的数据库连接数量是有限的,当不使用数据库时,一定要
断开连接,使得其他用户可以连接数据库。


总结:
finally代码块:定义一定自行的代码。

               通常用于关闭资源。


数据库操作过程说明:
public void method() throws NoException
{
    连接数据库;
    操作数据;//throw new NoException();
    断开连接;//该动作,无论操作数据是否成功,一定要关闭资源。
    try
    {
        连接数据库;
        操作数据;//throw new NoException();
    }
    catch(SQLException e)
    {
        会对数据库进行异常处理;
        throw new NoException();//告诉别人数据库操作过程中出现异常了。
    }
    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 ExceptionDemo3 {public static void main(String[] args) {Demo d = new Demo();try{int x=d.div(4,-1);System.out.println(x);}catch (FuShuException e){System.out.println(e.toString());}finally{System.out.println("关闭数据库连接");}System.out.println("Hello World!");}}


0 0