java Foundation (21): Exceptions

Keywords: Java jvm JDK

1. exceptions

What is an exception? The problem with Java code at runtime is exceptions.

In Java, exception information is encapsulated into a class. When problems arise, exception class objects are created and exception-related information (such as the location, cause, etc.) is thrown.

 

1.1 Abnormal Inheritance System

 

Exception classes are used to describe exceptions in Java.

Looking at the description of Exception in API, Exception class and its subclasses are a form of Throwable, which is used to represent possible exceptions in java programs and to require reasonable exception handling.

 

Looking further, we can see that Exception has an inheritance relationship, and its parent class is Throwable. Throwable is a superclass of all errors or exceptions in the Java language, namely ancestor classes.

 

 

 

In addition, in the exception Exception class, there is a subclass to specify that RuntimeException subclass, RuntimeException and other subclasses can only appear during the running of Java programs.

Looking at the Throwable class again, we can see that there is an Error on the level of exception Exception, which is a subclass of Throwable, which is used to represent serious errors that may occur in java programs. The only solution is to modify the code to avoid Error errors.

The summary of abnormal inheritance system:

Throwable: It's a superclass of all errors and exceptions (ancestors)

Error error

Exception compile-time exceptions, problems in compiling JAVA programs

Runtime Exception runtime exception, problems during JAVA program running

1.2 Distinction between exceptions and errors

Exception: An exception (XxxException) occurs during the compilation and execution of a program. We can deal with the exception in detail. If the exception is not handled, the program will end running.

The generation of anomalies is illustrated as follows:

public static void main(String[] args) {
    int[] arr = new int[3];
    System.out.println(arr[0]);
    System.out.println(arr[3]);
  // An array index crossover exception occurred while the sentence was running ArrayIndexOutOfBoundsException,Because no exception was handled, the program could not continue executing and the program ended.
    System.out.println("over"); // Because the above code has an exception, this code will not execute
}

Error: An error (XxxError) occurs while the program is running. Error usually does not have a specific way to handle it. The program will end running. Error errors often occur at the system level and are fed back to the jvm by the system where the jvm is located. We can't deal with it, we can only fix the code.

The generation of errors is illustrated as follows:

public static void main(String[] args) {
  int[] arr = new int[1024*1024*100];
  //A memory overflow error occurred while the sentence was running OutOfMemoryError,Open up too much array space, resulting in JVM Exceeding in allocating array space JVM Memory space, direct error.
}

1.3 Analysis of the Generation Process of Anomalies

Run the following program first, and the program will generate an array index crossover exception, ArrayIndex ofBoundsException. We use graphics to analyze the process of anomaly generation.

Tool class

class ArrayTools{
    //Get elements from a given array by a given corner label.
    public static int getElement(int[] arr,int index)    {
        int element = arr[index];
        return element;
    }
}

Test class

class ExceptionDemo2 {
    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");
    }
}

The above program execution process diagrams:

1.4 Throw an exception throw

When we write a program, we must consider the problem of the program. For example, when defining a method, the method needs to accept parameters. Then, when the calling method uses the accepted parameters, it first needs to make a legal judgment on the parameter data. If the data is not legal, it should tell the caller to pass in the legitimate data. In this case, the caller needs to be told by throwing an exception.

In java, a throw keyword is provided to throw a specified exception object. So, how exactly does throwing an exception work?

1. Create an exception object. Encapsulate some tips (information can be written by yourself).

2. This exception object needs to be notified to the caller. How do I tell you? How do I pass this exception object to the caller? It can be done by the keyword throw. Throw exception object;

Throw is used within a method to throw an exception object, pass the exception object to the caller, and end the execution of the current method.

Use format:

throw new exception class name (parameter);

For example:

throw new NullPointerException("To visit arr Array does not exist");
throw new ArrayIndexOutOfBoundsException("The index does not exist in the array and is out of range");

Below is the construction of the exception class ArrayIndexOutOfBoundsException and NullPointerException

After learning the format of throwing exceptions, we demonstrate the use of throw through the following program.

Write a tool class that provides the element values at the specified index of an array

class ArrayTools{
    //Returns the value of the element corresponding to the given index by a given array.
    public static int getElement(int[] arr,int index)    {
        /*
        If an exception occurs to the program, the JVM packages the exception object and throws it. But the information it provides is not enough. To be clearer, you need to throw exceptional information yourself.
If the following judgment condition is satisfied, when throw throws an exception object, the method can no longer continue to operate. This will end the execution of the current method and inform the caller of the exception. At this point, we need to solve it by exception.
        */
        if(arr==null){
            throw new NullPointerException("arr The pointing array does not exist");
        }
        if(index<0 || index>=arr.length){
            throw new ArrayIndexOutOfBoundsException("The wrong corner mark,"+index+"Indexes do not exist in arrays");
        }
        int element = arr[index];
        return element;
    }
}

Test class

class ExceptionDemo3 {
    public static void main(String[] args) {
        int[] arr = {34,12,67}; //Create array
        int num = ArrayTools.getElement(null,2);// Call the method to get the element at the specified index in the array
     //int num = ArrayTools.getElement(arr,5);// Call the method to get the element at the specified index in the array
        System.out.println("num="+num);//Print the captured element values
    }
}

1.5 Declaration of exception throws

Disclaimer: Identify the problem and report it to the caller. If a compile-time exception is thrown in a method without capture processing (explained later), then it must be declared by throws to be handled by the caller.

Declare exception format:

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

A code demonstration that declares exceptions:

class Demo{
    /*
    If a problem occurs when defining a function, it needs to be reported to the caller. It can be declared by using throws keyword in the method.
    */
    public void show(int x)throws Exception    {
        if(x>0){
            throw new Exception();
        } else {
            System.out.println("show run");
         }
    }
}

Throws are used to declare exception classes. If there may be many exception cases in this method, then after throws, we can write several exception classes separated by commas.

Multiple abnormal situations, such as:

public static int getElement(int[] arr,int index) throws NullPointerException, ArrayIndexOutOfBoundsException {
    if(arr==null){
        throw new NullPointerException("arr The pointing array does not exist");
    }
    if(index<0 || index>=arr.length){
        throw new ArrayIndexOutOfBoundsException("The wrong corner mark,"+index+"Indexes do not exist in arrays");
    }
    int element = arr[index];
    return element;
}

1.6 Capture exception try... catch... finally

Capture: Exception-specific statements are captured in Java and exceptions can be handled in a specified way

Capture exception format:

ctry: Write code in this block that may cause exceptions.

Catch: used to catch some kind of exception and handle the caught exception.

Finally: There are specific codes that need to be executed regardless of whether an exception occurs or not. In addition, because exceptions can cause program jumps, some statements can not be executed. And finally is to solve this problem, the code stored in the final code block is bound to be executed.

The demonstration is as follows:

class ExceptionDemo{
    public static void main(String[] args){ //throws ArrayIndexOutOfBoundsException
        try    {
              int[] arr = new int[3];
            System.out.println( arr[5] );// Will throw ArrayIndexOutOfBoundsException
            When an exception occurs, it must be handled in a way. Either capture or declare.
        }
        catch (ArrayIndexOutOfBoundsException e) { //What needs to be defined in parentheses? try What exception is thrown in parentheses defines what exception type. 
            System.out.println("Abnormal occurrence");
        } finally {
              arr = null; //Point the array to null,Clean up memory garbage through garbage collector
}
        System.out.println("Running result of program");
    }
}

1.7 try... catch... Combination of final exception handling

Try catch final combination: detect anomalies, pass them to catch processing, and release resources in final.

try catch combination: anomaly detection of code and passing anomaly detection to catch processing. The exception is captured and processed.

void show(){ //No need throws 
    try{
        throw new Exception();//Generate exceptions, directly capture processing
    }catch(Exception e){
    //Processing mode    
    }
}

A combination of try and catches: anomaly detection of code and passing the detected anomaly to catch processing. Each exception information is captured and processed differently.

void show(){ //No need throws 
    try{
        throw new Exception();//Generate exceptions, directly capture processing
    }catch(XxxException e){
    //Processing mode    
    }catch(YyyException e){
    //Processing mode    
    }catch(ZzzException e){
    //Processing mode    
    }
}

Note: This exception handling method requires that exceptions in multiple catches should not be the same, and if there is a relationship between multiple exceptions in catch and child parent exceptions, then child exceptions require catch processing above, and parent exceptions need catch processing below.

 

Try final combination: anomaly detection of code, detection of anomalies, because there is no catch, so the default jvm will be thrown. Exceptions are not captured and handled. But the resources opened by the function need to be turned off, all final. Only to shut down resources.

 

 

void show(){//Need throws 
    try{
        throw new Exception();
    }finally {
        //Release resources
    }
}

 

1.8 Runtime exception

 

 

RuntimeException and all its subclasses are run-time exceptions. NullPointerException, Array IndexOutOfBoundsException, etc. are run-time exceptions.

 

The characteristics of runtime exceptions:

 

A runtime exception is thrown in the method. There is no throws declaration in the method definition and no need for the caller to handle the exception.

 

Once runtime exceptions occur, programmers need to modify the source code.

 

 

class ExceptionDemo{
    public static void main(String[] args){
         method();
    }
    public static void method(){
        throw new RuntimeException();
    }
}

 

1.9 Details of Exceptions in Method Rewriting

 

 

When a subclass overrides a parent method, if the parent method declares an exception, the subclass can only declare a parent exception or a subclass of the exception, or not.

 

 

For example:

 

 

class Fu {
    public void method () throws RuntimeException {
   }
}
class Zi extends Fu {
    public void method() throws RuntimeException { }  //Throw the same exception as the parent class
    //public void method() throws NullPointerException{ } //Throw parent-child exception
}

 

When the parent method declares multiple exceptions, only a subset of multiple exceptions can be declared when the subclass overrides.

 

 

For example:

 

class Fu {
    public void method () throws NullPointerException, ClassCastException{
  }
}
class Zi extends Fu {
    public void method()throws NullPointerException, ClassCastException { }          public void method() throws NullPointerException{ } //Throws part of a parent exception
    public void method() throws ClassCastException { } //Throw part of the parent exception
}

 

When the overridden method has no exception declaration, the exception cannot be declared when the subclass overrides.

 

 

For example:

 

class Fu {
    public void method (){
  }
}
class Zi extends Fu {
    public void method() throws Exception { }//The wrong way
}

 

Examples: The following scenarios occur in parent classes, as well as in interfaces

Question: There is no exception declared in the interface, but an exception occurred when the subclass override method was implemented. What should we do?

Answer: No throws declaration can be made, only catch can be captured. What if we can't deal with all the problems? Throws continue in catch, but exceptions can only be thrown into RuntimeException subclasses.

 

 

 

 

interface Inter {
    public abstract void method();
}
class Zi implements Inter {
    public void method(){ //Cannot declare throws Exception
        int[] arr = null;
        if (arr == null) {
            //Capture processing only
            try{
throw new Exception("Dude, the array you define arr It's empty.!");
} catch(Exception e){
    System.out.println("No exception is thrown in the parent method, not in the subclass Exception Abnormal ");
        //We take exception objects. e,Use RuntimeException Abnormal mode throw
        throw new RuntimeException(e);
      }
    }
  }
}

 

1.10 Common methods of anomalies

 

 

In the Throwable class, we provide many methods to manipulate exception objects, which are commonly used as follows:

 

getMessage method: Returns the exception's detailed information string, which is the exception prompt information

toString method: Returns the name and detail string of the exception

printStackTrace: Outputs the name and detail string of the exception and the code location where the exception occurs in the console

Common Method Code Demonstration of Exceptions:

 

 

try {
    Person p= null;
    if (p==null) {
        throw new NullPointerException("Null pointer exception occurred, please check whether the object is null");
  }
} catch (NullPointerException e) {
    String message = e.getMesage();
    System.out.println(message ); 
    
    String result = e.toString();
    System.out.println(result);    
    
    e.printStackTrace(); 
}

 

2. Custom exceptions

 

 

In the above code, it is found that these exceptions are well defined within the JDK, and these exceptions are not easy to find. Writing is also inconvenient, so can you define exceptions by yourself?

 

The previous exceptions were described by Java through classes. If we encapsulate the problem as an object, the exception is to encapsulate the problem as an object. These exceptions are not easy to recognize and write. Can you define an exceptional name that meets the requirements of my program? Since class is used in JDK to describe exception information, we can also simulate this mechanism of Java. We define exception information and exception name by ourselves, so that the exception is more in line with the reading of our program. Accurately describe the class of exceptions you need.

 

2.1 Definition of custom exception classes

 

 

 

Read the exception source code: It is found that all exception classes in java inherit Throwable or a subclass of Throwable. This exception can then be throw n.

 

It shows that this anomaly system has a unique feature: throwability: it can be operated by throw keyword.

 

And consulting the source code of the exception subclass, we find that every exception calls the construction method of the parent class, passing the exception description information to the parent class, so that the parent class can encapsulate the exception information for us.

 

For example, NullPointerException exception class source code:

 

 

public class NullPointerException extends RuntimeException {
    public NullPointerException() {
        super();//Call the parent class constructor
    }
    public NullPointerException(String s) {
        super(s);//Constructing method of calling parent class with exception information
    }
}

 

Now let's define our own exception, a custom exception.

Format:

 

 

Class Exception name extends Exception{ //Or inheritance RuntimeException
    public Exception name(){
  }
    public Exception name(String s){ 
    super(s); 
  }
}

 

Demonstration of custom exception inheritance Exception

 

 

class MyException extends Exception{
    /*
    Why define the constructor, because you see that the exception description class in Java provides initialization methods for exception objects.
    */
    public MyException(){
        super();
    }
    public MyException(String message)    {
        super(message);// If custom exceptions require exception information, you can call the constructor of the parent class with string parameters.
    }
}

 

Demonstration of custom exception inheritance Runtime Exception

 

 

class MyException extends RuntimeException{
    /*
    Why define the constructor, because you see that the exception description class in Java provides initialization methods for exception objects.
    */
    MyException(){
        super();
    }
    MyException(String message)    {
        super(message);// If custom exceptions require exception information, you can call the constructor of the parent class with string parameters.
    }
}

 

2.2 Exercise on Customizing Exceptions

 

 

Define the Person class with name and age as two member variables.

 

In the parametric construction method of Person class, the age range is judged. If the age is negative or over 200 years old, the NoAgeException anomaly is thrown, which indicates that the age value is illegal.

 

Requirements: In the test class, parameter construction method is invoked to complete Person object creation and exception handling.

 

Custom exception class

 

 

class NoAgeException extends Exception{
    NoAgeException() {
        super();
    }

    NoAgeException(String message)    {
        super(message);
    }
}

 

Class Person

 

 

class Person{
    private String name;
    private int age;
    Person(String name,int age) throws NoAgeException    {
        //Add logical judgment.
        if(age<0 || age>200)        {
            throw new NoAgeException(age+",Illegal Age Value");
        }
        this.name = name;
        this.age = age;
    }
    //Definition Person Object corresponding string representation. cover Object Medium toString Method.
    public String toString()    {
        return "Person[name="+name+",age="+age+"]";
    }
}

 

Test class

 

 

class ExceptionDemo{
    public static void main(String[] args) {
        try {
            Person p = new Person("xiaoming",20);
            System.out.println(p);
        }
        catch (NoAgeException ex){
            System.out.println("Abnormal age");
        }
        System.out.println("over");
    }
}

 

To sum up, does the constructor throw this NoAgeException as inheriting Exception? Or inherit Runtime Exception?

To inherit Exception, a throws declaration must be made. Once the declaration is made, the caller is informed to capture it. Once the problem is solved, the caller's program will continue to execute.

Inheritance of Runtime Excpetion does not require throws declaration, at which point the call does not need to write capture code, because the call does not know the problem at all. Once NoAgeException occurs, the caller program stops, and a jvm displays the information to the screen so that the caller can see the problem and correct the code.

Posted by sup on Fri, 11 Oct 2019 01:43:58 -0700