Java learning 3-1_ exception handling

Exception handling

1.1 What is an exception

An exception is an instruction that causes a program interruption in the program

1.2 try catch to handle exceptions

The pseudo code is as follows:

try{
    
    
	// 有可能发生异常的代码段
}catch(异常类型1 对象名1){
    
    
	// 异常的处理操作
}catch(异常类型2 对象名2){
    
    
	// 异常的处理操作
}
finally{
    
    
	// 异常的统一出口
}

1.2.1 The processing flow of try catch

  1. Once an exception occurs, the system will automatically generate an instantiated object of the exception class
  2. Then, if the exception occurs in the try statement at this time, the matching catch statement will be automatically found and executed, if not in the try statement, the exception will be thrown
  3. All catches match the instantiated objects of the exception class according to the parameters of the method. If the match succeeds, it means that the catch block is processed
  4. Processing flow:
    • An exception occurs (JVM creates an exception object based on the exception situation-contains exception information)
    • main is not processed, and the exception is automatically thrown to the caller JVM of main
    • JVM responded to the exception information (display the exception information to the console, terminal processing)

1.2.2 finally

After the exception is processed, there is a finally statement in the exception processing format, then this statement will be used as the unified exit of the exception, regardless of whether an exception is generated, this code will be executed eventually

1.3 Exceptional architecture

Exception refers to Exception, Exception class, there is a parent class Throwable in Java (possibly thrown)

There are two subclasses of Throwable:

  1. Error: indicates an error, which is an incorrect operation issued by the JVM, which can only be avoided as much as possible, and cannot be handled with code
  2. Exception: generally indicates errors in all programs, so generally try...catch processing will be performed in the program.

Insert picture description here

1.4 Points to note about exception capture

  1. Catch coarser exceptions cannot be preceded by catching finer exceptions

  2. If for convenience, you can use Exception to capture all exceptions

  3. Multiple exception capture

    catch(异常类型1 |异常类型2 对象名){
          
          
    	//表示此块用于处理异常类型1 和 异常类型2 的异常信息
    }
    

1.5 Throw keyword

  1. The throw keyword is mainly used in the declaration of the method, which means that the method does not handle exceptions, but hands it to the caller for processing

  2. The throw keyword means that an exception is artificially thrown in the program, because from the perspective of the exception handling mechanism, once all exceptions are generated, what is actually thrown is an instantiated object of the exception class, and then this object can also be thrown Throw directly

    throw new Exception("异常");
    

1.6 The difference between RuntimeExcepion and Exception

As long as it is a subclass of RuntimeException , it means that the program does not need to use try catch for processing during operation. If an exception occurs, it will be processed by the JVM . Of course, it can also be handled by try catch.

1.7 Custom exception class

Write a subclass that inherits Exception and override the one-parameter construction method to complete the custom checked exception class

Write a subclass that inherits RuntimeException and rewrite the one-parameter construction method to complete the custom runtime exception type

class MyException extends Exception {
    
    
	public MyException(String msg) {
    
    
		super(msg);//调用Exception中有一个参数的构造方法
		
		//TODO: 做其他处理
	}
}

1.8 Exception Handling Interview

  1. Which part of try-catch-finally can be omitted?

    catch and finally can omit one of them, but not at the same time

    Catch is generally not omitted

  2. In try-catch-finally, if the catch is returned, will finally be executed?

    The code in finally will be executed

    Implementation process:

    1. Calculate the return value first, store the return value, and wait for the return

    2. Execute finally code block

    3. Return the previously stored return value

      /**
       * 基本数据类型会将副本保存,直接保存副本
       * 引用数据类型会保存引用,也就是地址,在返回时会被修改
       */
      public class Test {
              
              
          public static void main(String[] args) {
              
              
      
              System.out.println(getNum());
      
              System.out.println(getBook().name);
              
          }
      
          // 此方法返回20
          public static int getNum() {
              
              
      
              int a = 20;// 基本数据类型
              try {
              
              
                  return a;
              } catch (Exception e) {
              
              
                  return 0;
              } finally {
              
              
                  a = 10;
              }
      
          }
      
          // 此方法返回“水浒传”
          public static Book getBook() {
              
              
              Book b = new Book();
              try {
              
              
                  b.name = "西游记";
                  return b;
              } catch (Exception e) {
              
              
                  return null;
              } finally {
              
              
                  b.name = "水浒传";
              }
          }
      
          static class Book {
              
              
              String name;
          }
      }
      

      Note: The new basic data type stores values ​​directly in the stack memory

    note:

    1. The return value is determined before the finally operation, and cached, no matter what finally changes the value, the returned value will not change
    2. It is not recommended to include return in the finally code, because the program will exit early in the above process, that is to say, the returned value is not the value in try or catch
    3. If the JVM is stopped in a try or catch, finally will not be executed. For example, power failure--, or exit JVM through the following code: System.exit(0);

1.9 Common exceptions

1.9.1 Unchecked Exceptions in Java

abnormal description
ArithmeticException This exception is thrown when an abnormal operation condition occurs. For example, when an integer is "divided by zero", an instance of this class is thrown.
ArrayIndexOutOfBoundsException The exception thrown when accessing an array with an illegal index. If the index is negative or greater than or equal to the array size, the index is an illegal index.
ArrayStoreException An exception thrown when trying to store an object of the wrong type in an object array.
ClassCastException This exception is thrown when trying to cast an object to a subclass that is not an instance.
IllegalArgumentException The thrown exception indicates that an illegal or incorrect parameter was passed to the method.
IllegalMonitorStateException The thrown exception indicates that a thread has tried to wait for the monitor of the object, or tried to notify other monitors that are waiting for the object without specifying a monitor.
IllegalStateException A signal generated when a method is called at an illegal or inappropriate time. In other words, the Java environment or Java application is not in the proper state required by the requested operation.
IllegalThreadStateException The exception thrown when the thread is not in the proper state required by the requested operation.
IndexOutOfBoundsException Indicates that a sort index (such as sorting an array, string, or vector) is out of range.
NegativeArraySizeException If the application attempts to create an array with a negative size, this exception is thrown.
NullPointerException This exception is thrown when the application tries to use null where the object is needed
NumberFormatException This exception is thrown when the application attempts to convert a string into a numeric type, but the string cannot be converted into an appropriate format.
SecurityException An exception thrown by the security manager, indicating a security violation.

1.9.2 Checked Exceptions in Java

abnormal description
ClassNotFoundException When the application tried to load the class, the corresponding class could not be found and the exception was thrown.
CloneNotSupportedException When you call Objectclass clonemethod clone an object, but the object's class can not be achieved Cloneablewhen the interface Thrown.
IllegalAccessException This exception is thrown when access to a class is denied.
InstantiationException When you try to use the Classclass newInstanceyou create an instance of a class method, designated class object because it is an interface or an abstract class can not be instantiated Thrown.
InterruptedException A thread was interrupted by another thread and the exception was thrown.
NoSuchFieldException The requested variable does not exist

1.9.3 Exception method

Serial number Method and description
1 public String getMessage() returns detailed information about the exception that occurred. This message is initialized in the constructor of the Throwable class.
2 public Throwable getCause() returns a Throwable object representing the cause of the exception.
3 public String toString() uses the result of getMessage() to return the cascade name of the class.
4 public void printStackTrace() prints the result of toString() and the stack level to System.err, which is the error output stream.
5 public StackTraceElement [] getStackTrace() returns an array containing stack levels. The element with a subscript of 0 represents the top of the stack, and the last element represents the bottom of the method call stack.
6 public Throwable fillInStackTrace() fills the Throwable object stack level with the current call stack level and adds it to any previous information in the stack level.

Guess you like

Origin blog.csdn.net/Sky_Coolssy/article/details/108720020