Java exception handling mechanism

Java exception handling mechanism

Throw exception

  • Keywords throw and throws
  • Note: throw is different from throws!!
  • The exception thrown is used to resolve in the main method

Code example:

package Demo01;
public Application{
    public static void main(String[] args){
        try{
       new Application().test(10,0);
        }catch(ArithmeticException e){
            e.printStackTrace();
}
    }
    //Assuming that the method cannot handle the exception, we can throw the exception in the method
    public void test(int a,int b) throws ArithmeticExceptio{
        if(b==0){
            throw new ArithmeticException();  //Actively throw an exception, which is usually used in methods
        }
}
}

Catch exception

  • Keyword catch
  • When an exception occurs in our program, the program will generally stop running after reporting an error, but this is something we don't want to appear, so we will choose to capture the exception of the program and make it output in another form.

Code example:

package Demo02;
public Application{
    public static void main(String[] args){
        int a=666;
        int b=0;
        try{
            System.out.println(a/b);     //Code block to execute
        }catch(ArithmeticException e){   //Here, e can be defined by itself, and next to e is the type you want to capture
            System.out.println("The program is abnormal, b Cannot be 0");  /*If an exception occurs in the above code block, after the program throws an exception, it will be caught by the code block here, handle the exception here, and then execute later*/
        }finally{
            System.out.println("I'll come out anyway");   //finally keyword means that this code block will be executed regardless of whether there are exceptions in the above code
        }
    }
}


/*
Output content:
Program exception, b cannot be 0
 I'll come out anyway
*/
  • The "finally" keyword in this code can be omitted, but the "finally" keyword can be used to close when we learn about IO streams and resource related things later.
  • If you need to catch multiple exceptions, you only need to add a few more catches, but the level of the type in catch brackets cannot be from large to small, but can be from small to large.

Custom exception

  • The above two examples are built-in Exception classes in JAVA. Usually, these Exception classes can deal with most things in our life. However, there is another Exception that users can customize. When customizing exceptions, you only need to inherit the Exception class.

  • The use of user-defined exception classes in the program can be roughly divided into the following steps:

      1. Create a custom exception class.
         2. Pass in method throw Keyword throw exception object
         3. If you handle an exception in the method that currently throws an exception, you can use try-catch Statement capture and processing; Otherwise, it is passed at the method declaration throws Keyword indicates the exception to be thrown to the method caller to continue with the next operation.
         4. Catch and handle exceptions in the caller of the exception method.
    

Code example:

package Demo03;

//Custom exception class

public class OwnException extends Exception{
    private int detail;
    public OwnException(int a){
        this.detail=a;
    }
    
    //toString is used to print exception information
    @Override
    public String toString(){
        return "OwnException{"+"detail="+detail+"}";
    }
}

public class Test {
    
    //Write a code block with possible exceptions
    static void test(int a) throws OwnException{
        System.out.println("The parameters passed are"+a);  //Pass a parameter a
        if(a>10){
            throw new OwnException(a); //You can choose to catch or throw exceptions here. I choose to throw exceptions here
        }
        System.out.println("it is fine");  //If no exception occurs, the sentence it is fine is output
    }
    public static void main(String[] args){
       try{
           test(1);  //Run test in the main method, where a=1, and no exception will be triggered
       }catch(OwnException e){
           //You can also add some code to handle exceptions here
          System.out.println("OwnException>>"+e); //Catch exception and output exception
}
}
}


/*
The output content is:
it is fine
*/

Summary of practical application:

  • When dealing with run-time exceptions, logic is used to avoid them reasonably, and try catch is used to deal with them
  • You can add an additional catch(Exception) after multiple catches to handle exceptions that may be missed
  • For uncertain code, you can also use try catch to handle unclear exceptions
  • To handle exceptions, do not blindly call printStackTrace() to print out
  • Different businesses have different methods of handling exceptions
  • At the end of try catch, it's best to add finally to release the resources occupied by the program

Keywords: Java

Added by newbtophp on Mon, 27 Sep 2021 11:00:39 +0300