Java-exception handling mechanism

abnormal

1. What is an exception?

Errors in Java can be roughly divided into two categories:

One type is compile-time errors , which generally refer to syntax errors, which are generally avoidable.

The other type is runtime errors .

There is a set of exceptions specifically used to describe various runtime exceptions in Java , called exception classes . Java combined with exception classes provides a mechanism for handling errors.

The specific steps are:
when an error occurs in the program, an instantiated object of the exception class containing the error information is created, and the object is automatically submitted to the system, and the system transfers it to the code that can handle the exception for processing.

Exceptions can be divided into two categories: Error and Exception.

Error refers to a system error, generated by the JVM, and the program we wrote cannot handle it.

Exception refers to an error that occurs during the running of the program, and the program we write can handle it.

2. Abnormal use

The use of exceptions requires the use of two keywords try and catch , and these two keywords need to be used in combination. Use try to monitor the code that may throw an exception. Once the exception is caught, an exception object is generated and handed over to catch. Processing, the basic syntax is as follows.

try{
    
    
	//可能抛出异常的代码
}catch(Exception e){
    
    
	//处理异常
}
package com.song.exception;

public class Test {
    
    
	public static void main(String[] args) {
    
    
		try {
    
    
			int num = 10/10;
		}catch (Exception e) {
    
    
			// TODO: handle exception
			if(e.getMessage().equals("/ by zero")) {
    
    
			//用err的输出为红色
				System.err.println("分母不能为0");
			}
		}
	}
}

In addition to try and catch, you can also use the finally keyword to handle exceptions. What is the function of finally?

No matter whether the program throws an exception or not, the code in the finally code block will be executed, and finally usually follows the catch code block. The basic syntax is as follows.

try{
    
    
	//可能抛出异常的代码
}catch(Exception e){
    
    
	//处理异常
}finally{
    
    
	//必须执行的代码
}

one example:

package com.song.excepton;

public class Test2 {
    
    
	public static void main(String[] args) {
    
    
		System.out.println(test());
	}
	public static int test() {
    
    
		try {
    
    
			System.out.println("try...");
			return 10;
		}catch(Exception e) {
    
    
			
		}finally{
    
    
			System.out.println("finally...");
			return 20;
		}
	}

}

The output is:
try...
finally...
20

Explain that no matter whether the program throws an exception or not, the code in the finally code block will definitely be executed, and the return result in the finally will overwrite the result already returned in the try and return to the external caller, so the release of resources is generally performed finally.

3. Abnormal

Java encapsulates all errors that occur at runtime into classes, and is not a class, but a set of classes. At the same time, there is a hierarchical relationship between these classes, which are graded layer by layer from the tree structure . The class at the top is Throwable, which is the root node of all abnormal classes .

Throwable has two direct subclasses: Error and Exception. Throwable, Error, Exception are all stored in the java.lang package.

The subclasses of Error include VirtualMachineError (virtual machine exception), AWTError, IOError (input and output stream exception).

The subclasses of VirtualMachineError are StackOverflowError (stack memory overflow exception), OutOfMemoryError (memory overflow exception). Used to describe system problems such as memory overflow, which are system errors and cannot be handled.

The subclasses of Exception include IOException and RuntimeException. IOException is stored in the java.io package, and RuntimeException is stored in the java.lang package.

The subclasses of IOException include FileLockInterruptionException, FileNotFoundException, and FilerException. These exceptions are usually errors that occur during file transfer through IO streams.

The subclasses of RuntimeException include:

  • (1) ArithmeticException: Represents abnormal mathematical operation.
  • (2) ClassNotFoundException: Undefined exception of table class.
  • (3). IlllelArgumentException: indicates that the parameter format is incorrect.
  • (4), ArrayIndexOutOfBounds: indicates that the array index is out of bounds.
  • (5), NullPointException: indicates a null pointer exception.
  • (6) NoSuchMethodException: indicates that the method is undefined exception.
  • (7), NumberFormatException: Represents the type mismatch exception that occurs when other data types are converted to numeric types.
4、throw 和 throws

Throw and throws are two keywords that Java uses when handling exceptions. Both can be used to throw exceptions, but the methods and meanings used are completely different.

There are 3 ways to throw exceptions in Java:

  • (1) try-catch
  • (2) Using throw means that the developer actively throws an exception, that is, it must throw an exception when it reads the throw code. The basic syntax: throw new Exception() is a way to actively throw an exception based on the logic of the code.
public class Test {
    
    
	public static void main(String[] args) {
    
    
		int[] array = {
    
    1,2,3};
		test(array,2);
	}
	
	public static void test(int[] array,int index) {
    
    
		if(index >= 3 || index < 0) {
    
    
			try {
    
    
				throw new Exception();
			} catch (Exception e) {
    
    
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else {
    
    
			System.out.println(array[index]);
		}
	}
}
  • (3) Both try-catch and throw act on specific logic codes, and throws act on methods, which are used to describe the exceptions that the method may throw.

If the method throws is a RuntimeException or its subclass, it does not need to be handled when it is called externally, and the JVM will handle it.

If the method throws is an Exception or its subclass, it must be handled during external calls, otherwise an error will be reported.

public class Test {
    
    
	public static void main(String[] args) throws Exception {
    
    
		test("123");
	}
	
	public static void test(String str) throws Exception {
    
    
		int num = Integer.parseInt(str);
	}
	
}
5. Three ways of exception capture:
  • Automatically capture try-cath
  • throw Actively throw an exception
  • throws modifies methods that may throw exceptions
6, custom exception

In addition to using exceptions provided by Java, you can also customize exceptions based on requirements.

package com.song.exception;

public class MyNumberException extends RuntimeException {
    
    
	public MyNumberException(String error) {
    
    
		super(error);
	}
}
package com.song.exception;

public class Test {
    
    
	public static void main(String[] args){
    
    
		Test test = new Test();
		System.out.println(test.add("a"));
	}
	
	public int add(Object object){
    
    
		if(object instanceof Integer) {
    
    
			int num = (int)object;
			return ++num;
		}else {
    
    
			String error = "传入的参数不是整数类型";
			MyNumberException myNumberException = new MyNumberException(error);
			throw myNumberException;
		}
	}
}

Guess you like

Origin blog.csdn.net/qq_40220309/article/details/105623732