Java Day14

面向对象

N种内部类

public class Outer {

    private int id = 1;
    public void out(){
        System.out.println("这是外部类的方法");
    }

    public class Inner{
        public void in(){
            System.out.println("这是内部类的方法");
        }

        //获得外部类的私有属性
        public void getID(){
            System.out.println(id);
        }
    }


}

异常

Error和Exception

捕获和抛出异常

public class Test {
    public static void main(String[] args) {

        try {
            new Test().test(1,0);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        }

        //假设要捕获多个异常: 从小到大!

/*
        try {//try监控区域
            if (b==0){   // throw throws
                throw new ArithmeticException();//主动抛出异常
            }


            System.out.println(a/b);


        }catch (Error e){ //catch(想要捕获的异常类型!) 捕获异常
            System.out.println("Error");
        }catch (Exception e){
            System.out.println("Exception");
        }catch (Throwable e){
            System.out.println("Throwable");
        } finally { //处理善后工作
            System.out.println("finally");
        }
*/



    }

    //假设这个方法中,处理不了这个异常.方法上抛出异常
    public void test(int a,int b) throws ArithmeticException{
        if (b==0){   // throw throws
            throw new ArithmeticException();//主动抛出异常, 一般在方法中使用
        }
    }
}
public class Test2 {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;

        //Ctrl + Alt + T
        try {
            System.out.println(a/b);
        } catch (Exception e) {
            e.printStackTrace(); //打印错误的栈信息
        } finally {
        }

    }
}
posted @ 2020-12-07 21:13  Mr_NanZiXu  阅读(52)  评论(0)    收藏  举报