JavaSE learning notes (Day8)

Posted by daimoore on Sun, 02 Jan 2022 15:42:47 +0100

Day8

java exception concept

  • Exception: in the Java language, abnormal conditions during program execution are called "exceptions"

  • Exceptions (all abnormal conditions at runtime) that occur during the execution of Java programs can be divided into
    There are two types:

    • Error: serious problems that cannot be solved by the Java virtual machine, such as internal errors in the JVM system, resource exhaustion, etc. Generally, targeted processing is not prepared

    • Exception: general problems caused by programming errors or accidental external factors can be handled with targeted code.

      For example:

      1. Array subscript out of bounds: arrayindexoutofboundsexception

      2. There is no FileNotFoundException in the accessed file

      3. Null pointer exception: nullpointerexception

      4. Abnormal mathematical operation: arithmeticexception

      ​ and so on.

Abnormal system

  • Base class of exception: Throwable (all exceptions inherit this class)
  • Error serious problem
  • Exception is not a serious problem
    • RuntimeException and its subclasses can choose to handle or not handle exceptions that occur during operation (runtimeException is a superclass () of exceptions that may be thrown during normal operation of java virtual machine)
    • Non RuntimeException and its subclasses are exceptions during compilation. If they occur during compilation, they must be handled by themselves, otherwise the program cannot run

exception handling

  • When the main function receives a problem, there are two processing methods:

    a: Handle the problem yourself, and then continue to run
    b: There is no specific processing method, and only the jvm calling main can handle it

    The jvm has a default exception handling mechanism to handle the exception
    And the name of the exception and the information of the exception The location of the exception is printed on the console, and the program is stopped at the same time

    class test{
    	public static void main(String[] args){
            int a = 10;
            int b = 0;
            System.out.println(a/b);//An arithmetic error occurred here
            /*
            	For run-time exceptions, if you write your own processing scheme, it will be handed over to the JVM for default processing
            	--------
            	JVM Default processing method:
            	Print the abnormal information and exit the virtual machine
            	--------
            	You can write the processing method manually
            */
            
           System.out.println("Exception encountered. This line of code will no longer run");
        }
    }
    

Two methods of exception handling

try...catch...finally

try...catch Basic format for handling exceptions
    try    {
        Possible problem codes ;
    }catch(Exception name variable name){
        Handling of problems ;
    }finally{
        Release resources;
    }

Deformation format:
        try    {
            Possible problem codes ;
        }catch(Exception name variable name){
            Handling of problems ;
        }

Multiple exception handling:

         try {
                 Possible problem codes ;
        }catch(Exception name 1 variable name 1){
                 Handling of exceptions ;
        }catch (Exception name 2 variable name 2){
                  Handling of exceptions ;
        }....

             
matters needing attention:
a: try The less code in the, the better
b: catch Processing in,Even an output statement is OK.(Exception information cannot be hidden)
c:  finally{}Medium regardless try Have you encountered any exceptions, finally The code inside will be executed. We have some aftercare work to deal with here
d: Be as clear as possible. Don't use big ones.

Example

public class MyTest1 {
    public static void main(String[] args) {
        int a=10;
        int b=0;
        int[] arr={1,2,3};
        int[] arr2=null;
        //try {contains: code that may cause exceptions} catch (exception class name) {exception handling code}
        //Once the exception we caught occurs in the code in our try, catch will execute.
        try{
            System.out.println(a/b);//ArithmeticException
            System.out.println(arr[5]);//ArrayIndexOutOfBoundsException
            System.out.println(arr2[0]);//NullPointerException
        }catch (ArithmeticException e){
            System.out.println("Divisor is 0");
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println("Angle mark out of bounds");
        }catch (NullPointerException e){
            System.out.println("Object is null Yes");
        }catch (Exception e){//There is a child parent relationship. The parent must be followed
 
            System.out.println("Other exceptions");
        }
    }
}

throws

  • If you need to define functional methods, you need to expose the problems for the caller to deal with.
    Then the method is identified by throws.
 class MyTest {
    public static void main(String[] args) {
        try {
            test();
        }catch (ParseException e) {
            System.out.println("Parsing failed");
        }
        System.out.println("The following code");
        System.out.println("The following code");
        System.out.println("The following code");
    }
 
    public static void test() throws ParseException{
        //Compile time exception: it occurs during compilation and is not a RuntimeException or its subclasses. Compile time exceptions must be handled
        String str = "2020-10=10";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = simpleDateFormat.parse(str);
        //There are two ways to handle compile time exceptions: 1 Throw the exception, who calls who handles it, commonly known as throwing the pot.
        //2. Capture and process by yourself. Generally, if you throw it to main, don't throw it. Capture and process by yourself
    }
}

Several common methods of Throwable

/*    
    a:getMessage():                Get exception information and return string.
    b:toString():                Get the exception class name and exception information, and return a string.
    c:printStackTrace():        Get the exception class name and exception information, as well as the location of the exception in the program. Return value void
*/
class mytest2{
    public static void main(String[] args){
        int i = 10;
        int j = 0;
        try{
            System.out.println( i / j );
        }catch(Exception e){
             e.printStackTrace();//Print exception details
            System.out.println(e.getMessage());
            System.out.println(e.toString());
        }
        System.out.println("0.0");
    }
}

/*Operation results:

java.lang.ArithmeticException: / by zero
	at File_demo.mytest2.main(test.java:10)
/ by zero
java.lang.ArithmeticException: / by zero
0.0

*/

throws and throw

  • When a situation occurs inside a function method that the program cannot continue to run and needs to jump, throw the exception object with throw
  • The difference between throws and throw
    a:throws
    Used after the method declaration, followed by the exception class name
    It can be separated from multiple exception class names by commas
    Indicates that an exception is thrown and handled by the caller of the method
    throws indicates a possibility of exceptions that do not necessarily occur
    b:throw
    Used in the method body, followed by the exception object name
    Only one exception object name can be thrown
    This exception object can be a compile time exception object or a run-time exception object
    Indicates that an exception is thrown and handled by the statement in the method body
    Throw throws an exception, and executing throw must throw an exception

Characteristics and functions of finally keyword

finally features
The body of the finally controlled statement must be executed (provided that the jvm does not stop)
Special case: the jvm exits before finally executing (such as System.exit(0))
finally: used to release resources

Custom exception

  • Basic grammar
    public class exception class name extends exception / runtimeException {public exception class name (string MSG) {super (MSG);}}

  • Custom exception classes often do not write other methods, but only overload the construction methods that need to be used

  • Inherit Exception. After throw is used in the method, try catch or throws must be thrown in the method

public class ScoreExcption extends RuntimeException {
    //Customize the exception class and incorporate it into the Java exception system
    public ScoreExcption(String message) {
        super(message);
    }
}
  • Sample code
import java.util.Scanner;
 
public class MyTest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter your score 0--100");
        int score = sc.nextInt();
        int i = intputScore(score);
        System.out.println(i);
    }
 
    private static int intputScore(int score) {
        if(score>=0&&score<=100){
            return score;
        }else{
            //Once this happens, I can throw my custom exception
            throw new ScoreExcption("The result is illegal");
        }
 
    }
}
//Output results:
/*
Please enter your score 0 -- 100
101
Exception in thread "main" File_demo.ScoreExcption: The result is illegal
	at File_demo.MyTest.intputScore(test.java:30)
	at File_demo.MyTest.main(test.java:21)

Process finished with exit code 1
*/

Else

A: Exception considerations (for compile time exceptions)
a: When a subclass overrides a parent class method, the subclass method must throw the same exception or a subclass of the parent class exception, or it is possible that the subclass does not throw an exception. (the father is bad, and the son can't be worse than his father)
b: If the parent class throws multiple exceptions, when overriding the parent class, the child class can only throw the same exceptions or its subset. The child class cannot throw exceptions that the parent class does not have, or the child class can not throw exceptions.
c: If the overridden method does not throw an exception, the subclass method must not throw an exception. If an exception occurs in the subclass method, the subclass can only try, not throw

B: How to use exception handling
Principle: if the function can handle the problem internally, use try. If it cannot be handled, it will be handled by the caller. This is using throws
difference:
If subsequent programs need to continue running, try
Subsequent programs do not need to continue running to throw
C: Custom exception
If the JDK does not provide a corresponding exception, you need to customize the exception.

Topics: Java JavaEE JavaSE intellij-idea