[JavaEE advanced series from beginners to engineers] detailed explanation of exception handling and solutions in JavaEE (including throws declaration exception and throw keyword)

Article catalogue

?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ??

?? Homepage of personal blog:

Welcome to praise?? Collection?? Comments?? Follow??

?? Source code acquisition |?? Learning exchange |?? Business cooperation?? Private letter writer

?? More relevant knowledge??

??Detailed explanation of static method definition, method overload requirements and return function in JavaEE

??List interface common methods, essence summary

??Detailed introduction and use of all internal classes in JavaEE

??Common member methods in ArrayList collections

??Detailed explanation of String split cutting method in Java

??Four methods of replace in String

??Common methods of Stream flow in JavaEE

??Use of Stream knowledge points in JavaEE, summary of essence, and get started directly

??The difference between Filter and Listener in JavaWeb

??The most complete introduction to String classes in the history of JavaEE. Just learn the StringAPI

??[JavaEE advanced sequence | from Xiaobai to engineer] detailed explanation of exception handling and solutions in JavaEE Part 1 ??

1, View exception information

??public void printStackTrace()

// public void printStackTrace(): displays the details of the exception on the console
        try {
            String s=null;
            System.out.println(s.length());
        } catch (NullPointerException e) {


            e.printStackTrace();    //Display the details of the exception information on the console to give the programmer information to locate the exception

        }

        System.out.println("end");

??public String getMessage()

//public String getMessage(): returns a simple description of this exception
        try {
            String s="A";
            System.out.println(s.charAt(3));
        } catch (StringIndexOutOfBoundsException e) {

              //Error information can be recorded in the file
            //getMessage(): returns a simple description of this exception, which can record the error information in the file
            String message = e.getMessage();   //String index out of range: 3
            System.out.println(message);

        }
        System.out.println("end");

??public String toString()

//public String toString(): returns the type and simple description of this exception

    try {
            String s="A";
            System.out.println(s.charAt(3));
        } catch (StringIndexOutOfBoundsException e) {

            String s = e.toString();
            System.out.println(s);
            //java.lang.StringIndexOutOfBoundsException: String index out of range: 3

        }
        System.out.println("end");

2, Exception handling - throws declares an exception

1. Why do I need throws?

           *When an exception occurs inside a method and the method cannot handle it, you can"The header of this method declares this exception",
               
           "Give the exception to the caller for processing" (Equivalent to reporting exceptions and making disclaimers)

2. Format of throws

       format:
              Modifier return value type method name(parameter list) throws Exception class name 1,Exception class name 2{
	
                }

       example:
             public  static Date stringData(String date) throws ParseException {
                 
                }

//Note: the throws keyword can declare to throw multiple exceptions, which are separated by commas

Code demonstration

public class Demo {
    public static void main(String[] args) throws ParseException {
     
        Date date = stringData("2020-10-10");
        System.out.println(date);


    }


    /*
         Exception handling: throw an exception

          In the definition of method, throw exception is used
          Purpose: when there is an exception in the program, you can inform the caller and let the caller handle it
     */

    public  static Date stringData(String date) throws ParseException {

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");

        Date d = sf.parse(date);

        return  d;


    }
}

3. Usage scenarios of throws

    throws The idea of declaring an exception is:
    
            The current method does not know how to handle this type of exception. The exception should be handled by the caller at the upper level. If the caller does not know how to handle it, then continue to declare and throw the exception upward, and so on until main method

            If main Method does not know how to handle this type of exception, and it can also be used throws Declare to throw an exception, which will be handed to JVM Make default processing

4. Notes on the use of throws

       1.When overriding a method, the method overridden by a subclass throws The scope of the exception of cannot be greater than that of the parent method
       
       2.The parent class method does not declare to throw compile time exceptions, and the subclass overridden method cannot throw compile time exceptions
       
       3.It is recommended that the exceptions declared by the overridden method remain the same as the parent method

?? Case 1 demonstration (the exception of a subclass cannot be greater than the exception of a parent class)

class   Father{
    public  void test() throws  ParseException{

    }
}


class  son extends  Father{

    @Override


    //The exception of a subclass cannot be greater than the exception of a parent class

    //Exceptions of subclasses may not be written

    public  void test() throws Exception{

    }
}

?? Case 2 demonstration (the parent class does not throw an exception, and the subclass cannot throw an exception)

class  Father{
    public void test(){

    }
}


class  son extends  Father{

    @Override

    //If the parent class does not throw an exception, the child class cannot throw an exception
    //Methods that require subclasses should have fewer exceptions
    public  void test() throws  ParseException{

    }
}

3, Summary of two exception handling methods

statement throws:

    *Make an exception declaration for methods that may have exceptions
    
    *Inform the caller that there may be a problem with a method, and the method itself does not handle it, but let the caller handle it
   
   
capture try...catch:

     * Catch and handle possible exceptions
     
     * benefit:It can make the code continue to run

4, throw keyword

?? What can throw keyword do?

            Java Provided in throw Keyword, which can throw a specific exception during program operation
      
//throw is used to make exceptions               
//Note: after the throw exception, the following code will stop executing               

?? throw format

               format:
                       throw new Exception class name();
               example:    
                       throw  new Un18Exception("Illegal age anomaly");

?? Produce abnormal meaning

       * In the method, when the parameters passed are wrong and the program has no meaning to run, you can directly throw an exception and end the method
       
       * Inform the caller that there is a problem in the method and ask the caller to modify the code logic

5, The difference between throws and throw

throws
    * It is one of the exception handling methods, which is declared when the method is defined 
    
    * It is in the definition of method,Throw an exception upward for the caller to handle(Abnormal prompt)
 
    
--------------------------------------------------------------------------------------------
    
throw
   * It is a keyword that generates an exception and is used inside the method body
   
   * throw Is in the method,"raise an exception",Once implemented,Method will stop,amount to return
  
   * throw After the exception, the following code will stop executing

?? Series of popular columns??:

Series of articles on JavaEE advanced sequence | from Xiaobai to engineer

Series of articles on JavaEE project practice

Series of articles on JavaSwing project collection

pandas in data analysis series

6, Custom exception

1. Why do I need to customize exceptions?

             * JDK Although there are many exceptions, they may not meet our needs
                 
               At this point, we can define exception classes according to our business. For example, negative age and negative exam scores
       
//The meaning of custom exception: it is to make the error information of the console more visible   
// try catch is also applicable to custom exceptions

2. To customize exceptions

                   * Define exception classes
                 
                   * Write inheritance relationship
                 
                   * Empty parameter structure
                 
                   * Structure with parameters
                      
//Method of generating custom exception: throw new custom exception ("exception information");
//If the throw is a "compile time exception", you need to use the "throws declaration" at the method definition

?? Case 1 (custom compilation exception)

public class Un18Exception extends  Exception{

    //Nonparametric construction method
    public  Un18Exception(){
    }


    //Construction method with parameters
    public  Un18Exception(String message){
        super(message);
    }

}
public class Demo {


    public static void main(String[] args) {

        try {
            register();
        } catch (Un18Exception e) {
            e.printStackTrace();
        }


    }


    //Compile time exception: when it is generated, it must be handled (usually throws)

    public  static  void register() throws Un18Exception{  //Tell the caller that there may be exceptions in this method, which needs to be handled by the caller
        Scanner rd=new Scanner(System.in);
        int age=rd.nextInt();

        if(age>=18){
            System.out.println("login was successful");
        }else {
            //If an exception occurs, tell the user to handle it
//            throw exception object

            throw  new Un18Exception("Illegal age anomaly"); //Create exceptions and use them inside the method,
                                                   // Function similar to return

//            Throw new exception ("illegal age exception");
        }
    }

?? Case 2 (custom runtime exception)

//Custom runtime exception
public class Un18RuntimeException extends  RuntimeException{

    //Information describing the exception

    private  String message;

    //Nonparametric construction method
    public  Un18RuntimeException(){
    }


    //Construction method with parameters
    public  Un18RuntimeException(String message){
        super(message);
    }


    public void setMessage(String message) {
        this.message = message;
    }


}
import java.util.Scanner;

public class Demo {


    public static void main(String[] args) {


        register2();


    }


    /*   Runtime exception:
             Exception inherited from RuntimeException.
             There is no need to deal with it during compilation, which can be solved by optimizing the code logic
             So you can do it without throws

             There is no need to declare exception information when a runtime exception occurs
    */
    public  static  void register2() {

        Scanner rd=new Scanner(System.in);
        int age=rd.nextInt();

        if(age>=18){
            System.out.println("login was successful");
        }else {
            //If an exception occurs, tell the user to handle it
//            throw exception object

            throw  new Un18RuntimeException("Illegal age anomaly"); //Create exceptions and use them inside the method,
            // Function similar to return



//            Throw new exception ("illegal age exception");
        }
    }

}

7, Abnormal summary

 1.Classification of exceptions:"Compile time exception" and "Runtime exception" 
       *Compile time exception:
                  Inherited from Exception The exception of requires explicit processing
       *Runtime exception:
                  Inherited from RuntimeException No explicit processing is required

 2.Handling of exceptions: "throws" and "try-catch"
     
       * throws Significance of throwing:
                           Stop the method and tell the caller that there is a problem
                             
       * try-catch The meaning of capture:
                           So that the program can continue to execute

  3. Exception handling is usually for compile time exceptions. For run-time exceptions, it is necessary to strengthen the code logic to avoid occurrence

  4. Meaning of custom exception: 
                        Let the program prompt and error report more clearly

  5. Generate exception object:
                        throw new Exception class constructor();

Author:

If the article is helpful to you, you are welcome to give a praise or star. Your support is the greatest encouragement to the author. For deficiencies, you can make more corrections in the comment area and exchange and learn

Tags: Front-end Android Back-end Interview

Posted by Antnee on Wed, 10 Aug 2022 21:37:40 +0300