Java异常处理学习

抛出一个异常

        throw new ArrayIndexOutOfBoundsException();
        //手动抛出 2.JVM运行时帮你抛出


public class Launcher {
    public static void main(String[] args){
        m1();
    }
    public static void m1(){
        m2();
    }
    public static void m2(){
        int[] arr = new int[2];
        arr[2] =1;
    }
}
/*Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at Launcher.m2(Launcher.java:13)
at Launcher.m1(Launcher.java:9)
at Launcher.main(Launcher.java:6)
*/
public class Launcher {
    public static void main(String[] args){
        try{
            m1();
        }catch(ArrayIndexOutOfBoundsException e){
            e.printStackTrace();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            System.out.println("finally");
        }
    }
    public static void m1(){
        m2();
    }
    public static void m2(){
        int[] arr = new int[2];
        arr[2] =1;
    }
}
//catch可以有多个,顺序从小到大

自定义异常:

public class MyException extends Exception //继承自Exception
{
    public MyException(){
        super();
    }
    public MyException(String msg){
        super(msg);
    }
}

    public static void main(String[] args)throws MyException{
        throw new MyException("出现异常了");
    //  throw new NullPointerException();
    }
发布了22 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Joki233/article/details/53573364
今日推荐