java自定义异常类

来源:互联网 发布:视频特效素材软件 编辑:程序博客网 时间:2024/06/05 00:44
import lombok.Data;/** * @author 01369526 * */@Data@SuppressWarnings("serial")public class MyException extends RuntimeException implements Serializable{    private int errorcode;     public MyException(int errorcode,String message,Throwable throwable)     {         super(message,throwable);         this.errorcode=errorcode;     }}
import java.util.ArrayList;import java.util.List;/** * @author 01369526 * */public class Test {public void test(int a){    if (a==0) {        try {            List<Integer> list=new ArrayList<>();            list.add(666);            list.get(5);        } catch (Exception e) {            throw new MyException(666,"数组错误",e);        }    }}}
 */public class Main {    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub        try {            new Test().test(0);        }        catch (MyException exception) {            // TODO: handle exception            System.out.println(exception.getErrorcode()+"\n"+exception.getMessage()+"\n");            exception.printStackTrace();        }    }}

输出:

666数组错误MyException(errorcode=666)    at exception.Test.test(Test.java:20)    at exception.Main.main(Main.java:15)Caused by: java.lang.IndexOutOfBoundsException: Index: 5, Size: 1    at java.util.ArrayList.rangeCheck(ArrayList.java:653)    at java.util.ArrayList.get(ArrayList.java:429)    at exception.Test.test(Test.java:17)    ... 1 more
原创粉丝点击