Advanced Java ---- exception handling

An unexpected event that occurs when a program is running, which prevents the program from executing normally as expected by the programmer, which is an exception. When an exception occurs, do you allow the program to live and die, exit and terminate immediately, or output an error to the user? Or C language style: using function return value as execution state?.
Java provides a better solution: exception handling mechanism.
The exception handling mechanism enables the program to handle exceptions according to the preset exception handling logic of the code when exceptions occur, so that the program can return to normal and continue to execute as much as possible, and keep the code clear.
The exception in Java can be raised during the execution of the statement in the function or thrown manually by the programmer through the throw statement. As long as an exception is generated in the Java program, an exception object of the corresponding type will be used to encapsulate the exception, and JRE will try to find an exception handler to handle the exception.
Throwable class is the top-level parent class of Java exception type. Only when an object is an instance of throwable class (direct or indirect), it is an exception object and can be recognized by the exception handling mechanism. Some common exception classes are built in JDK, and we can also customize exceptions.

Java exception

What is a java exception

What has been introduced in the introduction java Abnormal, but it may not be clear to see these. Here is a short story:

        Case story (this case is only used for teaching. If there is any similarity in life, it will not be used
        (responsible)
        For example: the weather is fine today. The monitor wants to climb Dashu mountain and ride harrow bike
              Go, go to the mountains for fresh air
            Question 1: the mountain road suddenly collapsed. Fortunately, the monitor stopped in time, but it couldn't pass
            Yes, it's a serious problem
            Question 2: the monitor was driving a harrow bike. He suddenly found the bike halfway through
            There was no electricity. I changed my car on the way, and then it went smoothly
                Reach Dashu mountain. Such problems should be considered before departure
                of
            Question 3: the monitor is riding to enjoy the scenery and finds that the road ahead is not very good
            Go, there are small stones, and there is a flat road next to it
                He doesn't walk on a smooth road, so he likes to walk on small stones, resulting in a car
                It fell.
                Such a problem is a problem in the process of cycling.

Exceptions in Java

1. Serious problems

1. Serious problems: Error,Generally, we don't do this.
             For example, such problems may be encountered in the future
	         OOM,Out Of Memory,Memory overflow problem.
2. Exception: Exception
		Runtime exception: RuntimeException,We will not deal with such problems, because such similar problems are generally caused by the lack of rigorous code
		of
		Compile time exception: except not RuntimeException,All at compile time
		Exceptions must be handled. If they are not handled, the compilation fails and cannot run.
		If something goes wrong with the program, we don't do any export i,final JVM meeting
		Give a default processing method,
        The name of the exception class, the relevant reason, and the relevant information and information of the problem
        The position information is output on the console, and
         java The program will end and the subsequent code will not be executed.

public class ExpectionDemo1{
	public static void main(Stirng[] args){
	//The current time will be output here
		Data data = new Date();
		System.out.println(data);
		//But we want to convert the format. We need to convert the format to a general format
		//We often implement date conversion in development
		2021-12-24 10:57:00

		//The HH size represents a 24-hour scale
		//Hhlowercase represents the 12 hour scale
		SimpleDataFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System,out.println(s);
		

		String s1 = "2021-12-24";
		SimpleDateFormat sdfq = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date1 = null;
		//java.text.ParseException: Unparseable date: "2021-12-24"
		try{
			date1 = sdf1.parse(s1);
		}catch(ParseExpection e){
			e.printStackTrace();
		}
		System.out.println(date1);
	}
}

How to handle exceptions

1. try...catch...finally

Use format
Format 1:
try{
	Code for possible problems
}catch(Exception class name variable name){
	Handling of problems
}finally{
The code will be executed whether an error is reported or not
(In general, this is the code for putting resources)
}

Format 2:
try{
	Code that may cause problems;
}catch(Exception class name variable name){
  Some solutions to problems;
}

Format 3:Handle multiple exceptions
try{
	Possible problem code 1;
	Possible problem code 2;
	...
}catch(Exception class name 1 variable name 1){
	Some solutions to problems;
}catch(Exception class name 2 variable name 2){
	Some solutions to problems;
}


Multiple catch considerations:

1,When you can specify the exception type, try to specify the type as much as possible, and don't handle it with a large parent class
2,catch And catch Exceptions between are horizontal relationships, multiple catch There is no sequential relationship between exceptions. Once an exception occurs
    The parent class inherits the relationship. The parent class must be last
3,once try If there is a problem with the code inside, it will be matched catch The anomaly inside,
    Continue with the program try...catch...The following code, try The code inside stops at the step of reporting an error.

Code demonstration:

public class ExceptionDemo2{
	public static void main(String[] args){
		int a =10;
		int b = 0;
		if(b==0){
			System.out.println("Divisor cannot be 0");
		}else{
			System.out.println(a/b);
		}
	}

	int[] arr = null;
	
	//String --Date
	String s =  "2021-12-24 14";
	SimpleDateFormat sdf = new SimpleDateDFormat("yyyy-MM-dd HH:mm:ss");
	try{
		Date date = sdf.parse(s);
	}catch (ParseException e){
		System.out.println("Date conversion error!!!");
	}

	try{
		System.out.println(arr.length);
	}catch(NullPointerException e){
		System.out.println("Null pointer exception");
	}





}
	    JDK1.7 Then, a new processing method for multiple exceptions:
    try{
        Code that may cause problems;
    }catch(Exception class name 1 | Exception class name 2 | ...  Variable name){
        Tips for handling exceptions;
    }
    matters needing attention:
    1,The treatment methods are consistent. Although this method is relatively simple, it is not good enough. It aims at many types of problems,
        Only one solution is given
    2,catch The relationship between multiple exception types in must be a horizontal relationship, and there can be no inheritance relationship
public class ExceptionDemo3{
	public static void main(String[] args){
		int[] arr = null;
			
		//String -- date
		String s = "2021-12-24 14";
		SImplleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try{
			Date date = sdf.parse(s);
			//If an error is reported in the code in try
			//It will directly match the exceptions in catch
			//The rest of the code in try will not be executed
			System.out.println(date);
			
			System.out.println("world");
			System.out.println(arr.length);
		
		}catch (ParseException | NullpointerException e){
			System.out.println("Wrong report");
		}	
		System.out,println("hello");
	}
}
Methods of exception handling
  1. getMessage(): get exception information and return string
  2. toString(): get the exception class name and exception information, and return a string
  3. printStackTrace(): get the exception class name, exception information, and the location of the exception in the program. The return value is void
public class ExceptionDemo4{
	public static void main(String[] args){
		int a = 10;
		int b = 0;

		//ArithmeticException
		try{
			System.out.println(a/b);
		}catch(ArithmeticException e){
			//ArithmeticException e = new ArithmeticException();
            //The reason for the exception is printed
//            System.out.println(e.getMessage());

            //java.lang.ArithmeticException: / by zero
            //Exception class name: cause of the problem
//            System.out.println(e.toString());

            //Through observation, it is found that the print exception result automatically handled by the JVM by default is the same as when we did not do any processing before
            //We have to deal with it. If we don't deal with it, once an exception occurs, the following code will not run
            //After we do the processing, the following code will run normally
            e.printStackTrace();
		}
		String s = "2021-12-24 14";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = sdf.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        System.out.println("hello");	}
}

2.throws

	In the future development process, in some cases, we do not have permission to handle exceptions at all
    In other words, we can't deal with it at all, just don't deal with it.
    In order to solve this problem and ensure the normal operation of the program
    Java In this case, another way to solve the exception is provided: throws Throw (following method)
format
throws Exception class name
 Write after the method parentheses and before the braces

matters needing attention:

       1,main Try not to throw an exception in the previous method, because the program will stop and the subsequent code will not be executed
            However, in order to make it convenient for you to see the code in class, I will throw it directly,
            When developing, don't main method.

        2,Exceptions thrown during compilation do not need to be handled inside the method, but are handled by the caller calling the method in the future
        3,Run time exceptions may not be thrown, but once called, the following code will not be executed after an error
        4,It is best to throw a specific exception type, which is also recommended,Multiple exceptions can be thrown, separated by commas
public class ExceptionDemo{
	public static void main(String[] args){
		        //There is no exception handled in the method, and the caller must handle it
//        try {
//            fun();
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }

//        fun();

		try {
            fun1();
        }catch (NullPointerException e){
            e.printStackTrace();
        }


        System.out.println("hello");



		public static void fun() throws ParseExpection,NullPointerException{
			String s = "2021-12-24 14";
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = sdf.parse(s);
			System.out.println(date);
		}
		public static void fun() throws NullPointerException{
			int[] arr = null;
			System.out.println(arr.length);
		}
	}
}

throw method

	Used in the method body, followed by the exception object name
	Only one exception object name can be thrown
	Indicates that an exception is thrown and handled by the statement in the method body
        throw An exception is thrown and executed throw Must have thrown some kind of exception.
The difference between the two
 throws: 
        Used after the method declaration, followed by the class name of the exception
        It can be separated from multiple exception class names by commas
        Indicates that an exception may occur and is thrown to the caller for processing. It indicates a possibility,
        This exception does not necessarily occur
    throw: 
        Used in the method body, followed by the exception object name
        Only one exception object name can be thrown
        Indicates that an exception is thrown and handled by the statement in the method body
        throw An exception is thrown and executed throw Must have thrown some kind of exception
public class ExceptionDemo6 {
    public static void main(String[] args) {
        try {
            fun();
        }catch (ArithmeticException e){ //ArithmeticException e = new ArithmeticException()
            e.printStackTrace();
        }


        System.out.println("hello");
    }

    public static void fun(){
        int a = 10;
        int b = 0;

        if(b==0){
            System.out.println("An error is reported. The divisor cannot be 0");
            throw new ArithmeticException();
        }else {
            System.out.println(a/b);
        }
    }
}
 finally: Final meaning
        stay try...When handling exceptions, an exception is usually added at the end finally
        The statement body controlled by it will be executed. Generally, it contains code related to releasing resources
    try...catch...finally
public class ExceptionDemo7 {
    public static void main(String[] args) {
        String s = "2021-12-24 14:32:12";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            Date date = sdf.parse(s);
            System.out.println(date);
        }catch (ParseException e){
            e.printStackTrace();
        }finally {
            //It will be executed whether an error is reported or not
            System.out.println("The code here will be executed!!!");
        }

    }
}

Interview questions

    Interview questions:
        final,finally and finalize Differences between

        final:The final meaning can modify classes, member variables and member methods
            Decorated class: class cannot be inherited
            Decorated member variable: variable becomes constant
            Decorated member method: method cannot be overridden
        finally:It is a part of exception handling. Generally, it is used to release resources. Generally, it will be executed
            Under special circumstances: System.exit(0);
        finalize: yes Object Class, which is used for manual garbage collection, but it does not have to be called to start the collection.

        If catch There are return Statement, please finally Will your code still execute?
        If yes, where return Before or return After. return between
public class ExceptionDemo8 {
    public static void main(String[] args) throws ParseException{
//        int a = 10;
//        int b = 0;
//        int c = 0;
//
//        fun();
//
//        try {
//            //Stop the program
            System.exit(0);
//            c = a/b;
//        }catch (ArithmeticException e){
//            e.printStackTrace();
//        }finally {
//            System.out.println("this is the content in finally");
//        }

        System.out.println(fun());

    }

    public static int fun() {

        int a = 10;
        String s = "2021-12-24 14";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            a =30;
            Date date = sdf.parse(s);
            System.out.println(date);
            a = 40;
        }catch (ParseException e){
            a = 50;
            return a;//50
        }finally {
//            System.out.println(a);
            a = 70;
            int b = 80;
//            return b;
//            return a;
        }

//        System.out.println(a);
//
        return a;


    }


}

Abnormal precautions:
        1,When a subclass overrides a parent method, the subclass's method must throw the same exception or a subclass of the parent exception.(Father is broken,A son cannot be worse than his father)
        2,If the parent class throws multiple exceptions,When subclass overrides parent class,
            You can only throw the same exception or a subset of it,A subclass cannot throw an exception without a parent class
        3,If the overridden method does not throw an exception,Then subclass methods must not throw exceptions,
            If a compile time exception occurs in a subclass method,Then subclasses can only try,No throws

class A{
    public void fun(){

    }
}

class B extends A{
    @Override
    public void fun(){
        String s = "2021-12-24 14";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = sdf.parse(s);
        }catch (ParseException e){
            e.printStackTrace();
        }

    }
}

public class ExceptionDemo9 {
    public static void main(String[] args) throws NullPointerException,ParseException,ArithmeticException {
        B b = new B();
        b.fun();
    }
}

Keywords: Java Back-end

Added by threaders on Wed, 29 Dec 2021 22:56:17 +0200