Java [Road] - Exception Handling

abnormal

Of irregularities and has been described in the form of packaged objects by class java. Described abnormal situation class, called exception class. Code and the previous normal process handling code issues combined flow now normal code and the code-processing problems, to improve readability. In fact, an exception is java object-oriented thinking through the problem became objects package, with the exception classes be described. Different problems will be specifically described by different classes, such as the subscript bounds, null pointers. Many problems, the class is meant to describe a lot, which was drawn up in common, form a system abnormality, the final question (abnormal condition) to be divided into two categories: error and Exception (abnormal);

concept

  • In unusual circumstances that occurred during operation
  • An exception is a class, an exception is to create an exception object and throw an exception object.

    Java is a way to handle exceptions interrupt handling.

  • Abnormal does not refer to syntax errors, wrong grammar, the compiler does not pass, will not produce bytecode files, do not run

Exception root class Throwable

Feature

  • Throwable and its subclasses have all the disposable nature
  • Extension are a subclass of the class name with his father as a suffix, strong reading

classification

Error

The severity of the problem is thrown jvm, this problem is generally not targeted treatment, directly modify the program.

Exception (abnormal)

  • Feature

    When an exception occurs, can be corrected by means of the code, the program continues to run, that must be dealt with.

  • Category: According to at compile time or run time to check abnormal divided into two types.

    • Abnormal compile time: checked abnormal

      At compile time, it will check, if not handle the exception, the compiler fails. (E.g., date formatting exception)

      • Category: In addition to the special sub-category system RuntimeException, Exception and its subclasses are.

        • IOException
        • ClassNotFoundException
        • CloneNotSupportException
    • Abnormal operating time: runtime anomalies

      Directly compile, run time, abnormalities.

      • RuntimeException and its subclasses

Common method

  • public void printStackTrace()

    • Print details of the exception.
    • Contains the type of abnormality, reasons for abnormality, further comprising the locations of the anomalies,
  • public String getMessage()

    • Gets the reason the exception occurred.
    • To the user when it prompts the wrong reasons.

Abnormal generation process

Below subscript bounds exception ( ArrayIndexOutofBoundsException), for example, as follows:

public class ExceptionDemo {
    public static void main(String[] args) {
        int[] arr = { 34, 12, 67 };
        int num = ArrayTools.getElement(arr, 4);
        System.out.println("num=" + num);
        System.out.println("over");
    }
}

class ArrayTools {
    // 对给定的数组通过给定的角标获取元素。
    public static int getElement(int[] arr, int index) {
        int element = arr[index];
        return element;
    }
}

Diagram

After an exception occurs, the function ends, the latter statement is no longer accessible, throw an exception in this case ourselves, abnormal information to customize the code below.

class ArrayTools {
    // 对给定的数组通过给定的角标获取元素。
    public static int getElement(int[] arr, int index) {
        if(arr == null)
            throw new NullPointerException("数组的引用不能为空"); //throw抛出一个异常对象
        if(index >= arr.length)
            throw new ArrayIndexOutOfBoundsException("数组越界了:"+index);
        if(index < 0)
            throw new ArrayIndexOutOfBoundsException("数组的角标不能为负数:"+index);

        int element = arr[index];
        return element;
    }
}

Throw an exception

During the execution of Java program such as abnormal, it generates an exception class object, the exception object will be submitted to the Java runtime system, a process known as throw (throw) exception.

Format: throw new Exception class name (parameters)

E.g:

throw new NullPointerException("要访问的arr数组不存在");
throw new ArrayIndexOutOfBoundsException("该索引在数组中不存在,已超出范围");

Exception object generated:

Automatic generation: the program is running, the virtual machine detects a problem occurred in the program, if appropriate handler is not found in the current code, it will automatically create an instance of an object corresponds to a class of anomaly in the background and throw

Manually create: Exception exception = new ClassCastException (); create good does not throw an exception object does not have any influence on the program, and create a common objects, like

For example:

package java_demo_2.exceptiondemo;

/**
 * @ClassName: Demo02_Exception
 * @author: benjamin
 * @version: 1.0
 * @description: TODO
 * @createTime: 2019/07/21/15:47
 */

public class Demo02_Exception {
    public static void main(String[] args) {
//创建一个数组
        int[] arr = {2, 4, 52, 2};
//根据索引找对应的元素
        int index = 4;
        int element = getElement(arr, index);
        System.out.println(element);
        System.out.println("over");
    }

    /*
    根据 索引找到数组中对应的元素
    */
    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;
    }
}

operation result:

Then we will throw after throw an exception through, that is, after the issue back to the caller, the caller has to use two methods, one is to continue to issue statements out using throws claims processing, and the other is to capture process .

Exception Handling System

If an exception occurs, we will immediately terminate the program, so we have to handle exceptions:

  1. In the method does not handle, but dished out a statement by the caller of the method to deal with (throws).
  2. To handle exceptions using the try-catch block of statements in the method.

Statement throws an exception

concept

It indicates that the current method does not handle the exception, but rather to remind the caller of the method to handle exceptions.

format

Modifier return type method name (parameter) throws exception classes 1, 2 ... exception classes {}

Note: in the methods of throws declaration statement that throw exception list, the exception type behind throws exception type can be produced in the process, may be its parent.

throw and throws difference

  • throw

    • Objects thrown
    • Used within the function
    • throw new exception class name (parameter), for example: throw new NullPointerException ( "arr array to be accessed does not exist");
  • throws

    • Throw an exception class
    • Used on function
    • 可以抛多个,用,隔开

捕获异常try...catch...

概念

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

格式

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

    • try...catch....finally:自身需要处理异常,最终还得关闭资源。
    • 不论在try代码块中是否发生了异常事件, catch语句是否执行, catch语句是否有异常, catch语句中是否有return,finally块中的语句都会被执行
    • 当只有在try或者catch中调用退出JVM的相关方法,此时finally才不会执行,否则finally永远会执行
  • 注意

    多个异常采用一次捕捉多次处理

    格式

    try{
      编写可能会出现异常的代码
    }catch(异常类型A e){ 当try中出现A类型异常,就用该catch来捕获.
      处理异常的代码
      //记录日志/打印异常信息/继续抛出异常
    }catch(异常类型B e){ 当try中出现B类型异常,就用该catch来捕获.
      处理异常的代码
      //记录日志/打印异常信息/继续抛出异常
    }

    注意

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

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

自定义异常类

概念

对于负数为角标的情况,自己自定义一个用负数角标异常来表示。负数角标这种异常在java中并没有定义过,按照java异常的创建思想,将负数角标进行自定义描述,并封装成对象。这种自定义的问题描述称为自定义异常。

一般地,用户自定义异常类都是RuntimeException的子类。

自定义异常类通常需要编写几个重载的构造器。

自定义异常需要提供serialVersionUID

自定义的异常通过throw抛出。

自定义异常最重要的是异常类的名字,当异常出现时,可以根据名字判断异常类型。

步骤

  1. 自定义一个异常类XxxException,继承现有的异常类

    • 自定义编译期异常 :自定义类并继承于java.lang.Exception

    • 自定义运行时期异常:自定义类并继承于java.lang.RuntimeException

  2. 使用到自定义异常的其他类

    • 方法上:throws 异常类名;

    • 方法内:throw new 异常类名(参数);

代码举例:

模拟注册操作,如果用户名已存在,则抛出异常并提示:亲,该用户名已经被注册。

  1. 定义一个异常类: RegisterException继承与Exceptions

  2. 模拟登录操作,使用数组模拟数据库中存储的数据,并提供当前注册账号是否尊才方法用于判断。

    // 登录异常类
    public class RegisterException extends Exception{
    
        public RegisterException() {
            super();
        }
    
        public RegisterException(String message) {
            super(message);
        }
    }
    
    //自定义一个使用异常的类
    class Demo{
        //模拟数据库中已存在的账号
        private static String[] names = {"admin","tony","benjie"};
    
        public static void main(String[] args) {
            // 从键盘输入一个名字
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入一个名字:");
            String uname = scanner.next();
            // 调用方法
            try {
                checkUserName(uname);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public static boolean checkUserName(String uname) throws Exception{
            for(String name: names){
                if(name.equals(uname)){
                    throw new RegisterException("亲"+uname+"已经被注册了!");
                }
            }
            return true;
        }
    }

总结:

异常处理的5个关键字

try:执行可能产生异常的代码

catch:捕获异常

finally:无论是否发生异常,代码总被执行

throw:抛出异常。异常的生成阶段,手动抛出异常对象。throw new 异常类名(参数),例如:throw new NullPointerException("要访问的数组不存在");

throws:声明异常。异常的处理方式,声明方法可能要抛出的各种异常类。

Guess you like

Origin www.cnblogs.com/benjieqiang/p/11221449.html