java学习之异常之finally

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

package com.dreamy.day04;

/**
 * @author dreamy
 * 需求:在本程序中,对于除数时-1,也视为u是错误的是无法进行运算的,
 *    那么就需要对这个问题进行自定义的描述。
 */
class FuShuException extends Exception {//getMessage();
    private int value;
    public FuShuException() {
        super();
    }
    public FuShuException(String msg,int value) {
        super(msg);
        this.value=value;
    }
    public int getValue() {
        return value;
    }
    
    
}
class Demo02{
    int div(int a,int b) throws FuShuException{
        if(b<0) {
            throw new FuShuException("出现了除数是负数的情况",b);//手动通过throw关键字抛出一个自定义异常对象。
        }
        return a/b;
    }
}
public class ExceptionDemo02 {
    public static void main(String[] args) {
        Demo02 d=new Demo02();
        try {
            int x=d.div(4, -1);
            System.out.println("x:"+x);
        }catch (FuShuException e) {
            System.out.println(e.toString());
            return;
        }finally {//finall中存放的是一定会被执行的代码
            System.out.println("finall");
        }
        System.out.println("over");
    }
        
}
class NoException extends Exception{
    
    public NoException(String msg) {
        super(msg);
    }
}

/*
public void method() throws NoException{
     * 连接数据库;
     * 数据操作://throw new SQLException();
     * 关闭数据库://该动作,无论数据操作是否成功,一定要关闭资源
     * try{
     *         连接数据库;
     * 
     *         数据操作://throw new SQLException();
     * }catch(SQLException e){
     *         会对数据库进行异常处理;
     *         throw new NoException("数据没存成功");
     * }finally{
     *   关闭数据库;
     * }
}
*/

 

posted @ 2017-12-15 23:01  dreamy_java  阅读(133)  评论(0编辑  收藏  举报