26-Exception capture and handling

Abnormal capture and handling

Java is powerful in handling exceptions

Recognize the impact of abnormalities on the program

Exception refers to the instruction stream that caused the program to be interrupted.
After the error occurs, the entire program will not be executed in the intended manner but the execution will be interrupted. In order to ensure that the program can still be completed normally after a non-fatal error occurs, to ensure the smooth progress of the program.

Handling exceptions

Exception handling in Java can be accomplished by using the keywords try, catch, and finally. The basic processing structure is as follows:

try{
    
    
	// 可能出现异常的语句
}[catch (异常类型 异常对象){
    
    
	// 异常处理
}
catch (异常类型 异常对象){
    
    
	// 异常处理
}...][finally{
    
    
	// 不管异常是否处理都要执行
}]

Combinations that can be used: try...catch, try...catch...finally, try...finally.
At this time, when the exception is handled, the output is an object of the exception class, so if the object is directly printed, the exception information obtained is incomplete If you want to get the completed exception information, you can use the printStackTrace() method provided in the exception class to complete.
For the exception handling format, a finally block can also be added at the end to indicate the exit of exception handling, regardless of whether the program is abnormal or not.

Handling multiple exceptions

Several exceptions are generated. In this case, multiple catches can also be used to capture exceptions.
Exception type:

  • Forgot to input parameters: array out of bounds exception
  • Input type error: abnormal number format
  • Abnormal data: dividend must not be 0

Exception handling process

When performing exception handling, all exceptions that may have been clearly known to be generated are captured. Although a good code structure can be obtained, this kind of code writing is very troublesome, so if you want to make a reasonable exception, you must clear it after the exception is generated. What did the program do?
DzeAJg.png

  1. Exceptions will only occur during the running of the program, and once an exception occurs during the execution of the program, the specified type of exception class object will be instantiated automatically;
  2. If the program does not provide support for exception handling at this time, it will use the JVM default exception handling, first print the exception information and then exit the execution;
  3. If the program provides exception handling at this time, then the instantiated object of the generated exception class will be captured by the try statement;
  4. After try catches the exception, it performs a comparison with the matched catch exception type; if it matches, the catch is used for exception handling. If there is no successful match, it means that the exception cannot be handled;
  5. Finally, the finally statement is executed. After the finally is completed, it will further determine whether the current exception has been processed. If it is processed, it will continue to be executed, and if it is not processed, it will be handed over to the JVM for default processing.

In the whole exception handling, the actual operation is still an instantiated object of an exception class, so the instantiated object type of this exception class becomes the core key to understanding exception handling.
The largest type of exception that can be handled in a program is Throwable, which has two subcategories:

  • Error: The error occurred when the program has not been executed at this time and cannot be processed during development.
  • Exception: The developer can deal with the exception in the program.

Through analysis, it can be found that the instantiated object that will produce an exception when an exception occurs, then according to the object reference principle, it can be automatically transformed to the parent class. According to this logic, all exceptions can be handled by Exception.

catch(Exception e){
    
    
	e.printStackTrace();
}

When you are not sure which exceptions are generated, the processing is simple, and the problem to be dealt with is that the description of the error information is not clear, so it is a more convenient and clear way to handle exceptions separately.
When multiple exceptions are processed at the same time in the future, the exceptions with a large capture range should be placed after the exceptions with a small capture range.

throws keyword

Through the previous program, an exception may be generated in the program execution. Assuming a method is defined, the user should be clearly told what kind of exception will be generated. At this point, you can use the throws keyword on the method declaration to mark the exception type.

class Math{
    
    
	//这个代码执行时可能会产生算术异常,如果产生异常"调用处"处理
	public static int div(int x, int y) throws ArithmeticException{
    
    
		return x/y;
	}
}
main throws Exception{
    
    		//主方法向上抛出异常
	Math.div(10,2);
}

The main method itself is also a method, and the exceptions generated can also be thrown upward; it means that the JVM is responsible for handling the exceptions.

throw keyword

Throw means to manually throw an exception. At this time, an instantiated object of the exception is manually generated and the exception is thrown.

main{
    
    
	try{
    
    		//异常对象是手工定义的
		throw new Exception("自己跑着玩的对象。");
	} catch(Exception e){
    
    
		e.printStackTrace();
	}
	
}

Interview: Explain the difference between throws and throws?

  • throw: Used in code blocks, mainly to manually throw exception objects;
  • Throws: is used in the method definition, which means that the exceptions that this method may produce are clearly told to the calling place and handled by the calling place.

Exception handling model

class Math{
    
    
	//这个代码执行时可能会产生异常,如果产生异常"调用处"处理
	public static int div(int x, int y) throws Exception{
    
    
		int temp = 0;
		print("start");
		try{
    
    
			temp = x/y;
		} catch(Exception e){
    
    
			throw e; 		//向上抛异常对象
		} finally{
    
    
			print("end");
		}
		return temp;
	}
}
main{
    
    		
	try{
    
    
		Math.div(10,2);
	} catch (Exception e){
    
    
		e.printStackTrace();
	}
}

For this type, the catch in Math can be omitted. This type of exception handling format is very important in actual development (for resource access).

RuntimeException

As long as the method has throws, it will tell the user what kind of exception occurred.
If the current program execution requires the developer to process manually as long as the method defined by throws is used, the code is too cumbersome, so in the design process, a flexible optional exception handling parent class "RuntimeException" is provided. Subclasses of exceptions may not require mandatory handling.
Interview: Explain the difference between RuntimeException and Exception? List common RuntimeException.

  • RuntimeException is a subclass of Exception;
  • The exception marked by RuntimeException does not require mandatory handling, while the Exception exception must be mandatory.
  • 常见:NumberFormatException、ClassCastException、NullPointerException

Custom exception class

The JDK provides a large number of exception types, which may not be sufficient in actual development. At this time, consider custom exception types.
Two implementation schemes: inherit Exception or RuntimeException;

class BombException extends Exception{
    
    
	public BombException(String msg){
    
    
		super(msg);
	}
}
class Food{
    
    
	public static void eat(int num) throws BombException{
    
    
		if(num > 10 ){
    
    
			throw new BombException("TOO MUCH");
		} else{
    
    
			print("normal");
		}
	}
}

assert

After JDK1.4, an assertion function is added to confirm that the code must be the expected result after executing a certain line. The actual development assertion may not be correct, and there may be deviations, but this deviation should not affect the normal execution of the program.
Assertion is not set as a step that a program must execute in Java, and it can be turned on under a specific environment.

Guess you like

Origin blog.csdn.net/MARVEL_3000/article/details/111467178