Summary of JAVA Chapter 7 (exceptions)

Posted by witham on Mon, 18 Oct 2021 21:43:30 +0200

  1. What are the two subclasses of throwable? Briefly describe the difference between Java Error class and Exception class.  

Error: fatal exception. Under normal circumstances, it is unlikely to happen. An uncontrollable error has occurred in the identification system. The program can't handle it and can only intervene manually. For example, the errors StackOverflowError and OutOfMemoryError generated by the virtual machine.

Exception: non fatal exception. The program can handle. It is divided into checked exceptions detected by the compiler (checked exceptions) and unchecked exceptions not detected by the compiler (non checked exceptions).  

2. Exception s are divided into checked exceptions and unchecked exceptions. Please give examples respectively.    

-   checked exception: inherits from the Exception class. The code needs to handle the checked exception thrown by the API, either with a catch statement or directly with a throws statement. It can be understood as a compile time Exception. For example, IOException

-   unchecked exception: also known as runtimeException, it also inherits from Exception. However, all subclasses of runtimeException have a feature that the code can be compiled without handling their exceptions, so they are called unchecked exceptions. RuntimeException (runtime Exception) is an Exception that does not require try...catch... Or throws mechanisms to handle. Runtime Exception.

Exceptions derived from Error or RuntimeException are called unchecked exceptions, and all other exceptions become checked exceptions.

 

3. Please refer to the information and briefly describe the occurrence and causes of StackOverflowError and OutOfMemoryError.  

StackOverflowError:

>>Where it happens: the virtual machine stack and the local method stack

>>The stack frame depth generated by thread call exceeds the allowable depth of the virtual machine (for example, method B is called in method A, and then B calls C... this calls many layers, but the virtual machine can only provide A certain number of layers). However, the transfer depth of most virtual machine stacks can be dynamically expanded, so the probability of this problem is very low.

OutOfMemoryError

>>Place of occurrence: basically, the runtime data area (heap, stack, method area) of the virtual machine will occur

>>Cause: insufficient memory, memory overflow occurred

>>Processing: apply for more memory and adjust the startup parameters of the virtual machine

4. Briefly describe the two methods of exception handling, and illustrate the differences with examples.  

Display declaration throw:

for example

Implicit declaration throw:

For example:

class Pare2 {
    //NullPointerException example (throws declaration can be omitted after main method is signed)
    private static int[] x;
    public  static void main(String[] args){
        System.out.println(x[0]);
    }
    /*Judge the space before use
  if(x == null) {
        //Handle accordingly
    }*/
}

  Program capture processing:

 

try {
  statements
}
catch (ExceptionType1 ExceptionObject){
  Exception Handling 
}
catch (ExceptionType2 ExceptionObject) { 
  Exception Handling
}......
finally{
  Finally  Handling 
}

  Note: finally is the unified exit of this combined statement. It is generally used to clean up the aftermath, such as cleaning up resources, releasing connections, closing files, pipeline flow, etc. It is an optional part, but once selected, it must be executed.

5. Select the five subclasses of RuntimeException class and write the program that throws and catches the above subclass exceptions. (for example, arithmetic exception, null pointer exception, class conversion exception, array out of bounds exception, etc.)    

Null pointer exception:

public class TestShape {
    public static void main(String[] args) {
        int[] arr1=null;
        try{
            System.out.println(arr1[0]);
        }
        catch(NullPointerException e){
            System.out.println("happen NullPointerException");
        }
    }
}//A NullPointerException occurred

Array out of bounds exception:

public class TestShape {
    public static void main(String[] args) {
        int[] arr1=new int[5];
        try{
            System.out.println(arr1[7]);
        }
        catch(ArrayIndexOutOfBoundsException e){
            System.out.println("happen ArrayIndexOutOfBoundsException");
        }
    }
}//An ArrayIndexOutOfBoundsException occurred

Arithmetic exception:

public class TestShape {
    public static void main(String[] args) {
        try{
            System.out.println(3/0);
        }
        catch(ArithmeticException e){
            System.out.println("happen ArithmeticException");
        }
    }
}//An ArithmeticException occurred

Class conversion exception:

//This exception is reported when a number is cast into a string
public class TestShape {
    public static void main(String[] args) {
        try{
            Object x = new Integer(0);
            System.out.println((String)x);
        }
        catch(ClassCastException e){
            System.out.println("happen ClassCastException");
        }
    }
}//ClassCastException occurred

Array negative subscript exception:

public class TestShape {
    public static void main(String[] args) {
        try{
            int [] arr1=new int[-1];
        }
        catch(NegativeArraySizeException e){
            System.out.println("happen NegativeArraySizeException");
        }
    }
}//Negative arraysizeexception occurred

6. Customize an exception class according to a business scenario and throw the exception object in a scenario.  

public class TestShape {
    public static void function() throws NumberFormatException{
        String s = "abc";
        System.out.println(Double.parseDouble(s));
    }

    public static void main(String[] args) {
        try {
            function();
        } catch (NumberFormatException e) {
            System.err.println("Non data types cannot be converted.");
            //e.printStackTrace();
        }
    }
}

 

7. What is the difference between the throws statement in the exception and the throw statement? Please give an example.    

>>Throw: it means handling exceptions by yourself. Once throw is executed, the program will immediately turn to the exception handling stage, and the subsequent statements will no longer be executed, and the method will no longer return meaningful values!

>>Throws: it is used to declare all the exception information that may be thrown by a method. It declares the exception but does not handle it. Instead, it uploads the exception to whoever calls it. I will give it to whoever handles it.

difference:

>>Throws appears in the method function header, indicating that the method may throw exceptions, allowing throws to be followed by multiple exception types; Throw occurs in the function body, and throw throws an exception object, and there can only be one. When the method encounters an exception during execution, the exception information is encapsulated as an exception object, and then throw.

>>Throws indicates a possibility of exceptions, which do not necessarily occur; Throw throws an exception. Executing throw must throw an exception object.

public class TestShape {
    public static void main(String[] args) {
        String s = "abc";
        if(s.equals("abc")) {
            throw new NumberFormatException();
        } else {
            System.out.println(s);
        }
    }
}

public class TestShape {
    public static void function() throws NumberFormatException{
        String s = "abc";
        System.out.println(Double.parseDouble(s));
    }

    public static void main(String[] args) {
        try {
            function();
        } catch (NumberFormatException e) {
            System.err.println("Non data types cannot be converted.");
            //e.printStackTrace();
        }
    }
}

 

 

8. What is the function of the finally clause?

finally is the unified exit of this combined statement. It is generally used to clean up the aftermath, such as cleaning up resources, releasing connections, closing files, pipeline flow and so on. It is an optional part, but once selected, it must be executed.

public class TestShape {
    public static void main(String[] args) {
        System.out.println(testFinally());
    }
    private static int testFinally() {
        int temp = 100;
        try {
            System.out.println("Try");
            return ++temp;// return: the result of the is temporarily stored
        }
        finally {
            temp = 1;
            System.out.println(temp);
            System.out.println( "Finally" );
        }
    }
}

 

Topics: Java