About abnormal 07-

              Abnormal

Abnormal : refers to the abnormal circumstances in the course of program implementation, there will eventually lead to a non-JVM normal stop.

Abnormal system

The exception is the root class java.lang.Throwable, under which there are two subclasses: java.lang.Error and java.lang.Exception

  • Throwable common method

    public void printStackTrace() :打印异常的详细信息。包含了异常的类型,异常的原因,还包括异常出现的位置,在开发和调试阶段,都得使用printStackTrace。
    public String getMessage() :获取发生异常的原因。提示给用户的时候,就提示错误原因。
  • Category abnormal
    abnormal compile time : checked exceptions. At compile time, it will check, if not handle the exception, the compiler fails. (E.g., date formatting exception)
    runtime exception : runtime exception. In operation period, abnormalities at compile time, the compiler does not detect an abnormal operation (no error). (Such as math exception)

  • Abnormal generation process

Exception handling

Five key Java exception handling: the try , the catch , a finally , the throw , throws

  • Throw an exception throw

    When defining process, process parameters need to accept. When you call a method using the parameters received, first of all need to determine the legal parameters of the data, the data if legitimate, throwing an exception is required to tell the caller should tell the caller passes legitimate data. In java, it provides a throw keyword, which is used to throw an exception object specified

    Using the format : throw new exception class name (parameter);

        /*
         * 根据 索引找到数组中对应的元素
         */
        public static int getElement(int[] arr,int index){
           //判断  索引是否越界 
            if(index<0 || index>arr.length‐1){
                 /*
                 判断条件如果满足,当执行完throw抛出异常对象后,方法已经无法继续运算。
                 这时就会结束当前方法的执行,并将异常告知给调用者。这时就需要通过异常来解决。
                  */
                 throw new ArrayIndexOutOfBoundsException("哥们,角标越界了~~~");
            }
            int element = arr[index];
            return element;
        }
    }
  • Unusual statement throws

    If a problem arises, the problem will be described using throw an exception class that is thrown carried out, is about to issue returned to the caller of the method. So there are two ways for the caller, one is capture process, the other is to continue to issue statements out using the throws statement processing.

    声明异常:将问题标识出来,报告给调用者。如果方法内通过throw抛出了编译时异常,而没有捕获处理,那么必须通过throws进行声明,让调用者去处理。关键字throws运用于方法声明之上,用于表示当前方法不处理异常,而是提醒该方法的调用者来处理异常(抛出异常).

    使用格式:修饰符 返回值类型 方法名(参数) throws 异常类名1,异常类名2…{ }

    public class ThrowsDemo {
        public static void main(String[] args) throws IOException {
            read("a.txt");
        }
        public static void read(String path)throws FileNotFoundException, IOException {
            if (!path.equals("a.txt")) {//如果不是 a.txt这个文件
                // 我假设  如果不是 a.txt 认为 该文件不存在 是一个错误 也就是异常  throw
                throw new FileNotFoundException("文件不存在");
            }
            if (!path.equals("b.txt")) {
                throw new IOException();
            }
        }
    }
  • 捕获异常try...catch

    异常出现的话,会立刻终止程序,所以我们得处理异常:

    1. 该方法不处理,而是声明抛出,由该方法的调用者来处理(throws)。
    2. 在方法中使用try-catch的语句块来处理异常。

    捕获异常:Java中对异常有针对性的语句进行捕获,可以对出现的异常进行指定方式的处理。

    使用格式

    try{
         编写可能会出现异常的代码
    }catch(异常类型  e){
         处理异常的代码
         //记录日志/打印异常信息/继续抛出异常
    }

    finally代码块
    finally:有一些特定的代码无论异常是否发生,都需要执行。另外,因为异常会引发程序跳转,导致有些语句执行不到。而try语句块可能打开了一些物理资源(磁盘文件/网络连接/数据库连接等),我们都得在使用完之后,最终关闭打开的资源,这时需要使用try...catch....finally语句块。(注意:finally不能单独使用。当只有在try或者catch中调用退出JVM的相关方法,此时finally才不会执行,否则finally永远会执行。)

  • 异常注意事项

    1. 多个异常处理,一般使用一次捕获多次处理的方式

      try{
           编写可能会出现异常的代码
      }catch(异常类型A  e){  当try中出现A类型异常,就用该catch来捕获.
           处理异常的代码
           //记录日志/打印异常信息/继续抛出异常
      }catch(异常类型B  e){  当try中出现B类型异常,就用该catch来捕获.
           处理异常的代码
           //记录日志/打印异常信息/继续抛出异常
      }
      
      //注意:多个catch中的异常不能相同,并且若catch中的多个异常之间有子父类异
      //常的关系,那么子类异常要求在上面的catch处理,父类异常在下面的catch处理。
    2. 运行时异常被抛出可以不处理。即不捕获也不声明抛出。

    3. 如果finally有return语句,永远返回finally中的结果,避免该情况。

    4. 如果父类抛出了多个异常,子类重写父类方法时,抛出和父类相同的异常或者是父类异常的子类或者不抛出异常。

    5. 父类方法没有抛出异常,子类重写父类该方法时也不可抛出异常。此时子类产生该异常,只能捕获处理,不能声明抛出。

自定义异常

大部分异常都是JDK内部定义好的,但是实际开发中也会出现很多异常,这些异常很可能在JDK中
没有定义过(年龄负数问题,考试成绩负数问题在开发中根据自己业务的异常情况来定义异常类。

  • 异常类的自定义

    1. 自定义一个编译期异常: 自定义类 并继承于 java.lang.Exception 。
    2. 自定义一个运行时期的异常类:自定义类 并继承于 java.lang.RuntimeException 。
    // 业务逻辑异常
    public class RegisterException extends Exception {
        /** 空参构造 */
        public RegisterException() {
        }
        /**
         * @param message 表示异常提示
         */
        public RegisterException(String message) {
            super(message);
        }
      }
    /*-------------------------------------------------------------------------*/
    public class Demo {
        // 模拟数据库中已存在账号
        private static String[] names = {"bill","hill","jill"};
        public static void main(String[] args) {    
            //调用方法
            try{
                  // 可能出现异常的代码
                checkUsername("nill");
                System.out.println("注册成功");//如果没有异常就是注册成功
            }catch(RegisterException e){
                //处理异常
                e.printStackTrace();
            }
        }
        //判断当前注册账号是否存在
        //因为是编译期异常,又想调用者去处理 所以声明该异常
        public static boolean checkUsername(String uname) {
            for (String name : names) {
                if(name.equals(uname)){//如果名字在这里面 就抛出登陆异常
                    throw new RegisterException("亲"+name+"已经被注册了!");
                }
            }
            return true;
        }
    }

Guess you like

Origin www.cnblogs.com/dongdedong/p/11966487.html