Java异常

时间:2021-04-15 12:15:00   收藏:0   阅读:0

异常

异常体系结构

Error

Exception

异常处理机制

 

package com.exception;

public class Test {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        try {  //监控区域
            System.out.println(a/b);
        }catch (Error e){  //catch  捕获异常
            System.out.println("Error");
        }catch (Exception e){
            System.out.println("Exception");
        }catch (Throwable t){
            System.out.println("Throwable");
        } finally {  //处理善后工作,不论如何该语句总被执行
            System.out.println("finally");
        }

    }

}

 

 

throw为主动抛出异常,一般在方法中使用

 

package com.exception;

public class Test02 {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        new Test02().test(1,0);


    }
    public void test(int a,int b){
        if (b==0){
            throw new ArithmeticException();//主动抛出异常,一般在方法中使用
        }
        System.out.println(a/b);
    }
}

 

这样写也会抛出异常

package com.exception;

public class Test02 {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        new Test02().test(1,0);


    }
    public void test(int a,int b){
        if (b==0){
            throw new ArithmeticException();//主动抛出异常
        }
        
    }
}

 

假设在这个方法中处理不了这个异常,在方法上抛出异常

 

package com.exception;

public class Test02 {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        try {
            new Test02().test(1,0);
        } catch (ArithmeticException e) {
            System.out.println("catch");
        }


    }
    public void test(int a,int b) throws ArithmeticException{
        if (b==0){
            throw new ArithmeticException();//主动抛出异常
        }

    }
}

 

自定义异常

 

package com.demo.Demo12;

public class MyException extends Exception{

    private int detail;

    public MyException(int a){
        this.detail = a;
    }

    //toStying:打印信息

    @Override
    public String toString() {
        return "MyException{" + "detail=" + detail + ‘}‘;
    }
}

 

package com.demo.Demo12;

public class Test {
    static void test(int a) throws MyException {
        System.out.println("传递的参数为"+a);
        if (a>10){
            throw new MyException(a);
        }
        System.out.println("ok");
    }

    public static void main(String[] args) {

        try {
            test(11);
        }catch (MyException e){//e实际上是一段语句
            System.out.println(e);
        }

    }
}

 

实际应用中的经验总结

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!