Day17_ Abnormal mechanism

1, Abnormal mechanism

  1.   summary
    1. Exception is a consistency mechanism provided in Java to identify and respond to error conditions. Effective exception handling can make the program more robust and easy to debug.

      There are many reasons for exceptions, such as:

      1. The user entered illegal data
      2. The file to open does not exist
      3. Connection interrupted during network communication
      4. JVM memory overflow
      5. Some of these exceptions are caused by user errors, some are caused by program errors, and others are caused by physical errors.
    2. There are many reasons for exceptions, especially when the user input and the resource to be opened do not exist
      After these exceptions go wrong, the program life cycle will be terminated. Starting from the error code, the subsequent code will not be executed
      There is a class in Java that specifically simulates exceptions, Throwable. All exceptions inherit this class
  2. Previous common exceptions:
    1. Null pointer

    2. Subscript out of bounds

    3. Stack memory overflow

    4. Type conversion exception

  3. Inheritance system
    1.  
  4. Error

     

    1. Concept:

      Internal system errors. Such errors are handled by the system, and the program itself does not need to capture and handle them.  

      For example: oom (memory overflow error), virtualmachineerror (virtual machine error), stackoverflowerror (stack overflow error), etc. in this case, the JVM will choose to terminate the program.

    2. example:

      //Stack overflow error 
      public class TestError {
          public static void recursionMethod() {
              recursionMethod();// Infinite recursion
          }
          public static void main(String[] args) {
              recursionMethod();
          }
      }
      

      Error message:

      Exception in thread "main" java.lang.StackOverflowError

          at com.TestError.recursionMethod(TestError.java:5)

          at com.TestError.recursionMethod(TestError.java:5)

          at com.TestError.recursionMethod(TestError.java:5)

          at com.TestError.recursionMethod(TestError.java:5)

          at com.TestError.recursionMethod(TestError.java:5)

          at com.TestError.recursionMethod(TestError.java:5)

      ... ...

  5. Exception
    1. What is it?
      1. Exception is the parent of all exception classes. It is divided into non RuntimeException and RuntimeException.

      2. Non RuntimeException  
        It refers to the exceptions that need to be caught or handled during program compilation, such as IOException, custom exception, etc. This is a checked exception.
      3. RuntimeException 
        It refers to exceptions that do not need to be caught or handled during program compilation, such as NullPointerException, etc. Is an unchecked exception. It is usually caused by the carelessness of programmers. Such as null pointer exception, array out of bounds, type conversion exception, etc.
    2. common method
      1.   Two methods of exception handling
        1. throws: throw an exception to tell the caller what the problem might be
                    If you throw the exception to the caller, throw it out at the caller or solve it
        2. try...catch...: resolve exception
                       try {
                              High risk code;
                        } catch (exception type variable){
                              Solution;
                        }
      2. //	public static void main(String[] args) throws FileNotFoundException {
        	public static void main(String[] args) {
        		//Open resource file
        		try {
        			FileInputStream fis=new FileInputStream("D:/xxx");
        			System.out.println(123);
        //		} catch (Exception e) {
        		} catch (FileNotFoundException e) {
        			// Print error tracking stack frames, which are commonly used and suitable for programmers to troubleshoot
        //			e.printStackTrace();
        			//Obtain the error information, which is suitable for the user
        			String msg=e.getMessage();
        			System.out.println(msg);
        		}
        		System.out.println(456);
        	}

    3.   Try...catch...

      1. First kind

        1. try {
                    High risk code;
          }catch (exception type variable){
                    Solution;
          }

        2.  

          class A{
          	public void m1() throws IOException{
          		
          	}
          }
          class B extends A{
          	@Override
          	// Method overrides cannot have broader exceptions than the original method
          	//  The exception class thrown can be the class thrown in the parent class method or the corresponding subclass, but it cannot be its parent class
          	// If the parent class throws an exception a, the child class either throws a, or throws a subclass of a, or does not throw an exception, but it cannot be the parent of A
          	public void m1() throws FileNotFoundException{
          	}
          }

           

      2. Second
        1. try{
              High risk code;
          }Catch (exception type variable){
              Treatment scheme;
          }Catch (exception type variable){
              Treatment scheme;
          }...
        2. public static void main(String[] args) {
          		try {
          			FileInputStream fis = new FileInputStream("");
          		} catch (FileNotFoundException e) {
          			System.out.println("cannot find file");
          		} catch (NullPointerException e) {
          			System.out.println("Cannot be null");
          		} catch (Exception e) {
          			System.out.println("Other exceptions");
          		}
          	}
      3. Third
        1. Try (open resource){
                High risk code;
          }Catch (exception type variable){
                Treatment measures;
          }
        2. public static void main(String[] args) {
          		// Automatically close resources
          		try (FileInputStream fis = new FileInputStream("xxx");) {
          			// operation
          		} catch (Exception e) {
          			e.printStackTrace();
          		}
          	}
    4. Overwrite
      1. class A{
        	public void m1() throws IOException{
        		
        	}
        }
        class B extends A{
        	@Override
        	// Method overrides cannot have broader exceptions than the original method
        	//  The exception class thrown can be the class thrown in the parent class method or the corresponding subclass, but it cannot be its parent class
        	// If the parent class throws an exception a, the child class either throws a, or throws a subclass of a, or does not throw an exception, but it cannot be the parent of A
        	public void m1() throws FileNotFoundException{
        	}
        }
    5. Throws
      1. Throws throws throws an exception and does not handle the exception. It is a reminder mechanism
        If you call a method that throws an exception during translation, either you try...catch it, or you throw it
        throws is to throw an exception and will not solve the exception. It is generally used on the class library side (the called class)
        try...catch... Is used to solve exceptions. It is generally used for the client (for this class calling other classes, the client usually has a main method)
      2. 	public static void main(String[] args) throws FileNotFoundException {
        		m1();
        	}
        
        	public static void m1() throws FileNotFoundException {
        		m2();
        	}
        
        	public static void m2() throws FileNotFoundException {
        		m3();
        	}
        
        	public static void m3() throws FileNotFoundException {
        		FileInputStream fis = new FileInputStream("xxx");
        	}
        //Throwing exceptions can throw multiple exceptions at the same time, separated by commas and without sequence
        	public static void main(String[] args) throws Exception,
        		FileNotFoundException,IOException{
        	}
    6. Finally
      1. use
        finally: statement blocks that must be executed, such as open resources, need to be closed
        1. finally cannot appear alone. It must be used with try, or with try...catch
        2. There is only one case where the finally statement block does not execute, that is, close the virtual machine System.exit(0);
          	public static void main(String[] args) {
          		try {
          			int a=0;
          			int b=4;
          			//Divisor cannot be 0, an error will occur
          			int c=b/a;
          			System.out.println(c);
          		} catch (Exception e) {
          			e.printStackTrace();
          			// Termination method execution
          			return;
          			//System.exit(0);
          		}
          		finally {
          			//But finally will execute
          			System.out.println("22222");
          		}
          		//Unable to execute because there is a return on it
          		System.out.println("11111");
          	}
      2. be careful
        1. 	public static void main(String[] args) {
          		int result = m1();
          		//11
          		System.out.println(result);
          	}
          	public static int m1() {
          		int i=10;
          		try {
          			//Because there is a return in finally, and the priority is relatively high
          			//So when compiling, the return here is removed, only i++
          			return i++;
          //			i++;
          		} catch (Exception e) {
          			e.printStackTrace();
          		} finally{
          			System.out.println(i+"..............");
          		}
          		return i;
          	}

      3. Application scenario
        1.  
          	public static void main(String[] args) {
          		FileInputStream fis = null;
          		try {
          			//open resources
          			fis = new FileInputStream("xxx");
          			//xx operation
          		} catch (FileNotFoundException e) {
          			e.printStackTrace();
          		}finally {
          			//close resource
          			try {
          				//Judge whether to open the resource. If so, close it
          				if (fis!=null) {
          					fis.close();
          				}
          			} catch (IOException e) {
          				e.printStackTrace();
          			}
          		}
          	}
    7. Throw
      1. Anomaly source point

        Throw new exception class (error message);

        Reference custom exception

    8. Custom exception class
      1. custom
        1. Inherit an existing exception class
                Judge whether you should be a runtime Exception or a compile time Exception. If it is a runtime Exception, you need to inherit RuntimeException, otherwise you can inherit Exception
                In general, what we write must be compile time exceptions
        2. Public nonparametric construction
        3. Public parameterized construction, pass in a string, and pass the string to the parent class in the construction method
      2. public class UserException extends Exception {
        	public UserException() {
        
        	}
        
        	public UserException(String msg) {
        		super(msg);
        	}
        }
        public static void main(String[] args) throws UserException {
        		// Abnormal source
        		throw new UserException("xxxxxxxx");
        	}
      3. Application scenario
        1. public class UserService {
          	public static void login(String username,String password) throws UserException{
          		if (username.equals("admin")) {
          			if (password.equals("root")) {
          				// TODO login succeeded
          				// return "login succeeded";
          			}else {
          				// Incorrect TODO password
          				// return "the password is incorrect";
          				throw new UserException("Incorrect password");
          			}
          		}else{
          			// TODO user name is incorrect
          			// return "the user name is incorrect";
          			throw new UserException("Incorrect user name");
          		}
          	}
          }
          public class Client {
          	public static void main(String[] args) {
          		Scanner scanner = new Scanner(System.in);
          		System.out.println("Please enter your user name and password : ");
          		String username = scanner.next();
          		String password = scanner.next();
          		// System.out.println(username+" : "+password);
          		// String result = UserService.login(username, password);
          		// If (result. Equals){
          		// System.out.println("welcome back");
          		// }else{
          		// System.out.println(result);
          		// }
          		try {
          			UserService.login(username, password);
          			System.out.println("Login successful");
          		} catch (UserException e) {
          			// e.printStackTrace();
          			System.out.println(e.getMessage());
          		}
          	}
          }

Keywords: Java Back-end

Added by A2xA on Wed, 20 Oct 2021 21:24:12 +0300