Java learning day17: exception mechanism

1. Abnormal mechanism

one point one         What is the exception

Exception is a consistent mechanism provided in java to identify and respond to error situations. Effective exception handling can make the program simpler and more robust         Robustness: when the program encounters dangerous situations, it will not crash or shut down

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

After an exception occurs, the life cycle of the program will stop. Starting from the error code, the subsequent code will not be executed

In java, there is a class Throwable that specifically simulates exceptions. All exceptions inherit this class

one point two         Previous common exceptions

Null pointer         Subscript out of bounds         Stack memory overflow         Type conversion exception

one point three         Inheritance system

 1.4        Error

1. Errors in the system are handled by the system itself, and the program does not need to capture such errors

For example: oom (memory overflow error), etc

When this happens, the JVM will choose to terminate the program

2.Exception      

two point one         What is it?

Exception is the parent of all exception classes. It is divided into runtime exception and non runtime exception

-Non runtime exception

        It refers to exceptions, ioexceptions, custom exceptions, etc. that need to be caught or handled during program compilation

-Runtime exception

        It refers to exceptions that do not need to be caught or handled during program compilation, such as null pointer exceptions, which are generally caused by the carelessness of programmers, such as null pointer exceptions, array out of bounds, and type conversion exceptions

two point two         Common methods

  getMessage is used to print error messages to users

printStackTrace is used by programmers to debug

two point three         Two methods of exception handling

1.throws         Throw an exception to the caller and tell the caller what might happen here

                        If you give the exception to the caller, the caller can either throw it out or solve it in place

2.try{}catch(){}         Resolve exception

        public static void main(String[] args) throws FileNotFoundException {
			//Open resource file
		try{
			FileInputStream fis = new FileInputStream("D:/xxxx");
			System.out.println(123) ;			
		}catch(FileNotFoundException e){
			// Print error tracking stack frames, which are commonly used and suitable for programmers to troubleshoot
			// e.printStackTrace();
						
			// Get the error information and respond to the user
			String msg = e.getMessage();
			System.out.println(msg);
		}

2.4        try...catch....

First usage:

try {high risk code;}

Catch (exception type variable) {solution;}

 

  Second usage:

try {high risk code;}

Catch (exception type variable) {handling scheme;}

Catch (exception type variable) {handling scheme;}

Catch (exception type variable) {handling scheme;}

            try{
				FileInputStream fis = new FileInputStream("") ;
			}catch(FileNotFoundException e){
				System.out.println("cannot find file");
			}catch(NullPointerException e){
				System.out.println("Cannot be empty");
			}catch(Exception e){
				System.out.println("Other exceptions");
			}

The third usage:

Try (open resource) {high risk code;}

Catch (exception type variable) {handling measures;}

	    //Automatically close resources
		try(FileInputStream fis = new FileInputStream("xxx");){
			//operation
		}catch(Exception e){
			e.printStackTrace();
			
		}

When overriding a method, a subclass cannot have a broader exception than the parent class

2.5         throws

1. What is it

Throws throws throws an exception but does not resolve it. It is a reminder mechanism

2. Usage

If you call a method and the method throws an exception during compilation, then after you receive the exception, either solve try...catch... Or throw throws to your caller

public static void main(String[] args) {
			try {
				m1() ;
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	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");
}

Multiple exceptions can be thrown at the same time

//Throwing exceptions can throw multiple exceptions at the same time, separated by commas without sequence
	public static void main(String[] args) throws FileNotFoundException,IOException {

	}

3.Finally

three point one         What is finally

finally is a statement block that must be executed

        Usage scenario: if an open resource needs to be closed, the closed code can be written in finally

three point two         How to use

1. Finally cannot appear alone. It must be used with try or 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 = 3;
			// 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("2222");
		}
		// Unable to execute because there is a return on it
		System.out.println("1111");
	}

When you get to return, the program should have been terminated, but you see finally, so first execute the contents of the finally statement block, and then return to terminate the program

three point three         matters needing attention

 

  three point four         Application scenario

Close open resources

    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();
			}
		}
	}

4.Throw

four point one         What is throw

throw is the source of the exception

throw     new     Exception class (error message);

How to use: reference custom exception

5. Custom exception class

five point one         How to use it?

1. Inherit an existing exception class

        Judge whether the custom Exception class is a runtime Exception or a non runtime Exception. The runtime Exception inherits the RuntimeException, otherwise it inherits the Exception

        Generally, what we write is that the compile time Exception is an Exception

2. Public nonparametric structure

3. Public parameterized structure, the formal parameter is a string, and super(msg) is used in the method body; Pass to parent class

example:

public class UserException extends Exception{
		public UserException(){
			
		}
		public UserException(String message){
			super(message) ;
		}

}

  five point two         Application scenario

 

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() ;
			try{
				UserService.login(username, password);
				System.out.println("Login succeeded") ;
			}catch(UserException e){
				System.out.println(e.getMessage()) ;
			}
	}

}
public class UserService {

	public static void login(String username ,String password) throws UserException{
		if(username.equals("admin")){
			if(password.equals("root")){
	
			}else{
				throw new UserException("Incorrect password") ;
			}
		}else{
			throw new UserException("Incorrect user name") ;
		}
	}

Tags: Java Back-end

Posted on Sun, 24 Oct 2021 01:01:26 -0400 by phice