• java 异常


    什么是异常?

    在java中出现错误,创建异常类并抛出异常信息

    异常的继承体系

    Error:出现了就说明问题很大需要改代码

    Exception:问题不是很严重的

     1 }
     2     public static int getArray(int[] arr)throws Exception{
     3         //throw 关键字后面必须跟异常对象
     4         //throws 关键字后面必须跟异常类名
     5         if(arr==null){
     6             throw new Exception("数组为空");  //创建异常类对象
     7         }
     8         if(arr.length<4){
     9             throw new Exception("数组长度不够");
    10         }
    11         int i = arr[3]*2;
    12         return i;
    13     } 

     try{被检测的代码}

    catch{处理异常语句}

    finally{必须要执行的语句}

    try:该代码块中编写可能产生异常的代码。

    catch:用来进行某种异常的捕获,实现对捕获到的异常进行处理。

    finally:有一些特定的代码无论异常是否发生,都需要执行

    public static void main(String[] args) {
            // TODO 自动生成的方法存根
            int[] arr ={1,2,3};
            try{
                int res = getArray(arr);
                System.out.println(res);
            }catch(Exception ex){
                ex.printStackTrace();
            }finally{
                System.out.println("必须要执行的代码");
            }
            System.out.println("我执行了吗");
            
        }

    当有多个catch在一起时,如果有父类异常对象,放在最后一个catch代码块里,子类放前面

    当子类重写父类的方法时,如果父类声明了异常,子类可以声明父类异常或者父类异常的子类,或者不声明异常

    当父类方法没有声明异常时,子类重写方法不可以声明异常

    异常声明中常用的方法

    建议使用printStackTrace 最全面

    自定义异常类

     传一个不定参数,返回平均数不能有负数

    public static void main(String[] args) {
        double s = ping(2,2,2);
        System.out.println(s);
    }
    public static double ping(double...a){ double sum =0; //定义一个计时器 for(int i=0;i<a.length;i++){ //把可变参数看成一个数组,遍历得到传过来的每一个数 if(a[i]<0){           //声明异常,如果穿过来的参数小于0,就声明 throw new FUshuException("不可以传负数"); } sum = sum+a[i];         //接收所有的数 } return sum/a.length; //总数除数组的长度就是每个的平均数 }
  • 相关阅读:
    Tarjan
    uestc 方老师的分身IV
    Fleury(弗罗莱)算法求欧拉回路
    515D
    uestc 方老师的分身 II
    uestc SOUND OF DESTINY
    uestc WHITE ALBUM
    双向BFS
    【Tomcat】【3】报错 Illegal access: this web application instance has been stopped already. Could not load [org.apache.commons.pool.impl.CursorableLinkedList$Cursor]
    【JS】【25】把字符串转换为数字
  • 原文地址:https://www.cnblogs.com/wangrongchen/p/9186810.html
Copyright © 2020-2023  润新知