java exception and handling mechanism

Keywords: Java

1, Classification

1. Error

2. Exception

  • Compile time exception
  • Runtime exception


2, Processing mechanism

1. Catch exception

  • try-catch-finally

    try{
      //After an exception occurs, the code behind the try block exception will not be executed and will directly jump to the catch block
    }catch(Exception e){
      //Only when an exception occurs will it be executed
      //When you want to jump out of the catch block, execute finally first  
    }finally{
      //It is executed regardless of whether an exception occurs
      //It is generally used to close resources
    }
    //After processing, the program will continue to execute
    

    Exercise 1: when both catch and finally contain a return statement, how to execute it

    public class ExceptionDemo1{
      
      public static int method(){
        int i = 1;
        try{
          String name = null;
          if(name.equals("Tom")){
            System.out.println("name");
          }
        }catch(NullPointerException e){
          return 3;
        }finally{
          return 4;
        }
      }
    
      public static void main(String[] args){
        System.out.println(method());
      }
    }
    //The answer is output 4
    //Because finally needs to be executed anyway 
    

    Exercise 2: when both catch and finally contain a return statement, how to execute it

    public class ExceptionDemo1{
      
      public static int method(){
        int i = 1;
        try{
          String name = null;
          if(name.equals("Tom")){
            System.out.println("name");
          }
        }catch(NullPointerException e){
          return ++i;
        }finally{
          return ++i;
        }
      }
    
      public static void main(String[] args){
        System.out.println(method());
      }
    }
    //The return statement of the catch block can actually be split into i + + and return i
    //When return i is executed, because finally must be executed, skip to finally and continue to execute the code
    //finally can also be split into i + + and return i
    //When executing return, exit the method
    //The output is 3
    

    Exercise 3: how to execute catch if it contains a return statement

    public class ExceptionDemo1{
      
      public static int method(){
        int i = 1;
        try{
          String name = null;
          if(name.equals("Tom")){
            System.out.println("name");
          }
        }catch(NullPointerException e){
          return ++i; 
        }finally{
          ++i;
          System.out.println("i="+i);
        }
      }
    
      public static void main(String[] args){
        System.out.println(method());
      }
    }
    //When executing the return of catch, first save the result value with a temporary variable, temp=2, and then jump to finally.
    //After finally executing, return to catch
    //The output is
    //i=3
    //2
    

    Exercise 4: how to execute a try catch finally return statement

    public class ExceptionDemo1{
      
      public static int method(){
        int i = 1;
        try{
          String name = null;
          if(name.equals("Tom")){
            System.out.println("name");
          }
        }catch(NullPointerException e){
          return ++i; 
        }finally{
          ++i;
          System.out.println("i="+i);
        }
        return 5;
      }
    
      public static void main(String[] args){
        System.out.println(method());
      }
    }
    //After return in catch, return other than try catch finally will not be executed
    //The output results are the same as exercise 3
    


2. Throw an exception

  • try-finally

    try{
      //After an exception occurs, the code behind the try block exception will not be executed and will directly jump to the finally block
    }finally{
      //It is executed regardless of whether an exception occurs
    }
    //After processing, the program will not continue to execute, but throw the exception to the upper method
    

  • throws
    The exception information will be thrown to the upper method until the JVM prints out the exception information and terminates the program
    Method call: JVM > main() > f1() > f2()

  1. When compile time exceptions occur in f2(), if f2() does not use try catch processing, it will not use throws processing by default. You must explicitly throw exceptions

  2. If main(), f1() does not use try catch, it is also necessary to display an exception thrown

  3. Finally, when the JVM arrives, print out the exception information and terminate the program

    public class ExceptionDemo1 {
      //3. Same as step 2
    	public static void main(String[] args) throws FileNotFoundException {
    		f1();
    	}
    	//2. The compile time exception thrown by F2 () is equivalent to the compile time exception in f1(). The exception handling method should also be specified
    	public static void f1() throws FileNotFoundException{   
    		f2();
        }
        //1. If a compile time exception occurs, throw it to f1()   
        public static void f2() throws FileNotFoundException{   
            FileInputStream fi = new FileInputStream("C://test.txt");      
        }
    }
    

Details:

  1. For compile time exceptions, the program does not use throws by default, and the processing method must be explicitly specified
  2. For runtime exceptions, if the program does not handle them, the throw mode is adopted by default
  3. The exception thrown by a subclass must be consistent with the exception of the parent class, or it must be a subclass of the latter
  4. A try catch block can catch multiple exceptions. The order of catch should be that the child exception class comes first and the parent exception class comes second
  5. Catching exceptions is equivalent to leaving exceptions in the current class for processing. It is generally understood that one person carries all the exceptions
  6. Throwing an exception is commonly understood as throwing the pot. Try finally is also a kind of throwing the pot, but you have to do something before throwing the pot (execute the finally block)



3, Custom exception class

  1. Try to inherit runtime exceptions, so that the default processing mechanism can be adopted, and compile time exceptions must be handled
  2. Throw custom exception:
    throw new CustomException
    
  3. throw keyword: manually generate an exception class object, that is, a man-made error, for example (int a = 1/0)

Posted by tobeyt23 on Tue, 30 Nov 2021 20:22:57 -0800