java拾笔2_异常

catch必须从小类型异常的到大类型异常进行捕捉

catch(FileNotFoundException e){
 e.printStackTrace();//输出异常信息   
}

finally为了保证某一资源一定会释放,所以finally语句中写释放资源的代码:

public static void main(String[] args) throws IOException{
        FileInputStream fis=null;
        try {
            fis=new FileInputStream("c:/ab.txt");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally{
            fis.close();
        }
    }    

final,finally,finalize的区别:

 * final: 修饰变量,修饰方法,修饰类
 * finally:属于try,他里面的代码一定会执行(若遇到退出JVM时System.exit(0);除外)
 * finalize:
   * finalize()方法名
   * 1.finalize方法属于Object类
   * 2.使用finalize方法可以在垃圾回收机制中将对象(不用了的)从内存中清除出去

自定义异常类:

//NameLongException.java
public
class NameLongException extends Exception { //定义异常的时候一般提供两个构造方法 public NameLongException(){} public NameLongException(String msg){ super(msg); } }
public void reg(String name) throws NameLongException{
        if(name.length()>8){
            NameLongException e=new NameLongException("the name is longer");
            throw e;
        }
    }
    public static void main(String[] args) throws NameLongException {
        register r=new register();
        r.reg("sdoidderd");
    }
原文地址:https://www.cnblogs.com/xin-zhizhu/p/13178152.html