Java高级编程4-姜国海

①封装

class Student {
    public int age;
    public Student(){
        this.age = 0;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age){
        this.age = age;
    }
}

eclipse 可以自动生成set get 方法

可以控制读写权限,可以删掉set 然后变为只读

②异常处理

异常的属性:
1.string:异常的信息
2.编号,易于管理异常
3.错误的原因:异常链
异常类的根类 Throwable 子类 error Exception

error:不用处理,直接结束程序

Exception:可以进行异常处理

NullPointerException: 空指针异常

IndexOutOfBoundsException: 数组下标越界异常

ArithmeticException: 整数除零异常

RuntimeException:运行异常,程序员可以通过编程避免

浮点数除0不报错:结果INF

ClassCastException:类转换异常

Eg:
class Fruit {

}

class Apple extends Fruit  {

}

苹果类型的引用变量可以给水果类型的引用变量赋值

Fruit f;
Apple a;

f = a; //提升,隐含了一个提升
if(f instanceof Apple){//确保不出现类型转换异常
    a = (Apple) f; //向下的类型转换
}

if(null instanceof Apple){//返回false
}
Eg:
if(f instanceof string[]){}

好不相关的类型之间用instanceof 会在编译的时候报错

checked exception 检查异常 不能通过编程解决的异常
在Exception 类中去掉RuntimeException 之外的是检查异常

③检查异常



文件读写操作
FileInputStream file = new FileInputStream ('a.txt');
int c = file.read;
file.close();

编译器发现可能出现检查异常的代码都不可编译通过,两种处理方式
1.try{} catch{}
unreachable: 永远不可执行的语句java不可以编译
Eg:while(false)
多个catch时要按照由范围小到大写
catch可以一个可以多个 也可以没有
finally:这个分支一定会被执行,return语句之前也要执行

技巧
try{}
finally{
..//这里的语句一定会被执行
}

getMessage()
getCause()异常链
while(Throwable e){
    while(e!==null){
        System.out.println(e.getMessage());
        e = e.getCause();
    }
}

与下面等价
e.printStackTrace();


2.函数的异常返回 throws Exception

public static void a() throws Exception ,...{//抛出Throwable 类型的子类

}
检查异常要进行语法检查

class A {
    void a(){
        try{
        }catch(java.io.IOException){
            //这里检查上面的try里面有没有可能产生检查异常,发现没有语句,则编译不通过
        }
    }
}


④自定义异常类

pubic class MyException extends Exception {
    private int pains = 0;
    public MyException (String message, Exception e,int pains){
        super(message,e);
        this.pains = pains;  
    }
}

void a() throws AException{
    try{
    }catch(BException e){
        throws new AException(e);//异常转换
    }
}

⑤多态与异常

覆盖函数不可以抛出被覆盖函数没有声明的检查异常,只能更少或者相等
覆盖函数不可以比被覆盖函数访问权限低

猜你喜欢

转载自blog.csdn.net/l1558198727/article/details/80921298