Java-8 anomaly

abnormal

  • Means a non-normal exception occurred in operation during the program, such as user input errors, division by zero, the file to be processed does not exist, the array subscripts crossing the boundary. In the Java exception handling mechanism, the introduction of many used to describe and handle exceptions class, called exception class. Exception class definition contains information such abnormality and method of abnormality processing.
  • Exception handling process
  1. Throws an exception: in the implementation of a method, if an exception occurs, this method generates an object representing the anomaly, stop the current execution path, and the exception object submitted to the JRE.

  2. Capture exception: the exception is obtained after JRE, find the appropriate code to handle the exception. JRE look at the call stack method, starting from the method generates an exception back until you find the appropriate exception handling code so far.

        try {
            System.out.println(1 / 0);
        }catch (Exception e){
            System.out.println("出错了");
            e.printStackTrace();
        }
  • All abnormal root class is java.lang.Throwable, Throwable has derived the following two subclasses: Error and Exception, abnormal abnormal is divided into subjects and not subjects (a runtime exception) abnormal
  • Error wrong program can not handle, indicate more serious problems running the application. Most errors has nothing to do with the execution of the operation code writers, and that the problem code is running JVM (Java Virtual Machine) appears

RuntimeException abnormal runtime

  • Derived RuntimeException exceptions, such as by 0, subscript array bounds, null pointer, etc., which generates more frequent, troublesome process, if the impact statement or an explicit program will capture the readability and great operating efficiency. Thus automatically detected by the system and to their default exception handler (user does not have to handle them)
  • Processing logic determines needs to be increased

Unchecked exceptions CheckedException

  • Such an exception must be made at compile time, otherwise not compile
  • There are two unusual approach: using the "try / catch" catch the exception, use the "throws" unusual statement
  • try catch finally, you can have multiple catch
        try {
            System.out.println("可能异常的语句");
            System.out.println(1 / 0);
        }catch (Exception e){
            System.out.println("出错了");
            //e.printStackTrace();
        }finally {
            System.out.println("总算结束了");
        }
  • Reading file
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class TestReadFile {
    public static void main(String[] args) {
        FileReader fileReader = null;
        try {
            fileReader = new FileReader("D:\\data\\shuihu.txt");
            char c1 = (char)fileReader.read();
            System.out.println(c1);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) { //多个异常,子类在前,父类在后
            e.printStackTrace();
        }finally {
            if(fileReader != null){
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

throws

  • When CheckedException produce, not necessarily immediately deal with it, you can then throws out an exception,
  • If a method might produce some kind of anomaly, but it does not determine how to deal with this anomaly, an exception should be based specification exception in the header declarations of methods which might be thrown. If a method throws more checked exceptions, it must process all the exceptions listed in the first section, separated by commas between
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class TestThrow {
    public static void main(String[] args) {
        String path = "D:\\data\\shuihu.txt";
        //处理异常,或者在方法后继续标记抛出异常
        try {
            readFile(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static void readFile(String path) throws IOException {

        FileReader fileReader = new FileReader(path);
        char c1 = (char)fileReader.read();
        System.out.println(c1);

        if(fileReader != null){
            try {
                fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Custom exception

  • If the custom exception class inherits the Exception class, was inspected exceptions, must be handled; If you do not want to deal with, you can make custom exception class RuntimeException exception classes inherit runtime.
  • Traditionally, custom exception class constructor should include two: a default constructor, a constructor with other details.
public class TestDefinedException {
    public static void main(String[] args) {
        Person p = new Person();
        p.setAge(10000);
        p.setName("高尔基 西莫维奇·彼什科夫");
    }
}

class Person{
    private int age;
    private String name;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if(age < 0 || age > 130){
            //运行时异常
            throw new IllegalAgeException("年龄有误");
        }else{
            this.age = age;
        }
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        if(name.length()>10){
            try {
                //Name的受检异常,必须trycatch或方法后标记抛出
                throw new IllegalNameException("名字太长");
            } catch (IllegalNameException e) {
                e.printStackTrace();
            }
        }else {
            this.name = name;
        }
    }
}

class IllegalAgeException extends RuntimeException{
    /*
    运行时异常
     */
    public IllegalAgeException(){
    }
    public IllegalAgeException(String info){
        super(info);
    }
}
class IllegalNameException extends Exception{
    public IllegalNameException(){}
    public IllegalNameException(String info){
        super(info);
    }
}
Published 72 original articles · won praise 80 · views 70000 +

Guess you like

Origin blog.csdn.net/weixin_40450867/article/details/104268860