异常机制(Exception)(一)

异常机制 

 

 

Exception直接子类

 

 

空指针异常(NullPointerException)

练习

package cn.Exception;

public class Test01 {
    public static void main(String[] args) {
        computer c=null;        //空指针异常,对象是null,调用了对象的方法和属性。    
        if(c!=null) {
            c.start();
        }
        
    }
}
class computer{
    void start() {
        System.out.println("启动");
    }
}

try-catch-finally

 

 典型示例

package cn.Exception;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Test02 {
    public static void main(String[] args) {
        FileReader f=null;      //d
        try {
        f=new FileReader("C:/Users/Administrator/Desktop/sun/a.txt");   //要抛FileNotFoundException异常//FileReader 用来读取字符文件的便捷类
        char c=(char)f.read();                                        //要抛IOException异常
        char c2=(char)f.read();
        System.out.println(""+c+c2);   //添加上“”,代表字符串相连
        
        }catch(FileNotFoundException e) {    //FileNotFoundException是IOException的子类,一般情况下子类放在前面,如果放后面,就会报父类已经处理的错误
            e.printStackTrace();
        }
        catch( IOException e){
            e.printStackTrace();
        }
        finally {
            try {
                if(f!=null)      //如果f是空的就不执行了,f不是空的,执行关闭代码。
                {
                    f.close();   //抛异常
                }
            }
            catch(Exception e) {
                e.printStackTrace();
            }
        }
    }
}

 执行顺序

 最后执行return,finally里有return,则会将前面的返回值覆盖,因此不建议在finally里建立返回值。

 

               

posted on 2019-07-19 11:56  Mentality  阅读(308)  评论(0编辑  收藏  举报