java: exception handling

java: exception handling

1 Introduction

The exception capture structure of java language consists of try, catch and finally. Among them, the try statement stores java statements that may have exceptions; The catch program block is used to trigger the caught exception; Finally is the last execution part. No matter how the try statement block code exits, the finally statement block will be executed.

tips:python's exception capture (else is: if there is no exception to execute this code, except can add multiple possible exceptions in one line)

Divisor cannot be 0
 Success or failure,Will eventually be implemented

2 grammar

idea quick input try/catch statement:



Statements in catch code block, commonly used functions to obtain information about exceptions:

e.getMessage(): used to output the error nature;

toString(): gives the type and nature of the exception;

printStackTrace(): indicates the type, nature, stack level and location of the exception in the program.

package com.base;

import java.util.Arrays;

public class Excep {
    public static void main(String[] args) {
        try {
            System.out.println(1/0);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (ArithmeticException e1) {
            System.out.println(e1.getMessage());
            System.out.println("------");
            System.out.println(e1.toString());
            System.out.println("------");
            System.out.println(Arrays.toString(e1.getStackTrace()));
            System.out.println("------");
            e1.printStackTrace();
        }finally {
            System.out.println("Final");
        }
    }
}


3 finally statement block

The complete exception handling statement must include the finally statement. The finally statement will be executed no matter whether there are exceptions in the program or not, and whether the try catch between is successfully executed.

In the following four special cases, finally blocks will not be executed:

An exception occurred in the finally statement block;
In the previous code, System.exit() is used to exit the program;
The thread where the program is located dies;
Turn off the CPU.

4 custom exception

You can customize the Exception class by inheriting the Exception class. The steps are as follows:

(1) Create custom exception class
(2) Throw an exception object through the throw keyword in the method
(3) If an exception is handled in the method that currently throws an exception, you can use the try catch statement block to catch and handle it. Otherwise, indicate the exception to be thrown to the method caller through the throws keyword in the method declaration, and continue to the next step
(4) Catch and handle exceptions in the caller of the exception method

Custom exception:

package com.base;

public class XXException extends Exception{
    public XXException(String errMsg){
        //Parent class construction method
        super(errMsg);
    }
}


The first method: the main method adds throws to throw the exception

public class TryExc {
    //Define method and throw exception
    static int avg(int num1,int num2) throws XXException {
        if(num1<0||num1>20){
            throw new XXException("num1 stay[1,20]between"); //error message
        }
        if(num2<30||num2>50){
            throw new XXException("num2 stay[30,50]between");
        }
        return (num1+num2)/2;
    }

    public static void main(String[] args) throws XXException {
        System.out.println(TryExc.avg(-1, 10));
    }
}


The second way:

ctrl+alt+T after System.out.println(TryExc.avg(-1, 10)), add a try catch statement:


5 throw an exception in the method - throw, throw keyword

If an exception may occur in a method, but you don't want to handle it in the current method, you can throw an exception in the method using the throw and throw keywords

5.1 throws

The throws keyword is usually used when declaring a method to specify the exceptions that the method may throw. Multiple exceptions can be separated by commas.

package com.base;

public class Shoot {
    static void pop() throws NegativeArraySizeException{
        int[] arr=new int[-4];
    }

    public static void main(String[] args) {
        try {
            pop();
        } catch (NegativeArraySizeException e) {
            e.printStackTrace();
            System.out.println("pop()Method");
        }
    }
}

Note: after throwing the exception to the upper level with the throws keyword, if you don't want to handle the exception, you can continue to throw it up, but finally there must be code that can handle the exception.

If it is Error, RuntimeException or their subclasses, you can declare the exception to be thrown without using the throws keyword. The compilation can still pass smoothly, but it will be thrown by the system at run time.

5.2 throw keyword throws an exception

The throw keyword is usually used in the method body and throws an exception object. The program terminates immediately when the throw statement is executed, and the following statements are not executed. After throwing an exception, if you want to catch and handle the exception in the upper level code, you need to use the throws keyword in the method throwing the exception and specify the exception to be thrown in the method declaration; If you want to catch the exception thrown by throw, you must use the try catch statement block.

Throw is usually used to throw user-defined exceptions.

Custom exception class:

package com.base;

public class MyException extends Exception{ //Create custom exception class
    String msg;
    public MyException(String ErrorMessage){
        msg=ErrorMessage;
    }
    //Note that to call e.getMessage() of the custom class to print information, you need to override the getMessage() method of the Exception class
    //Otherwise, the value returned by e.getMessage() of the custom class is null
    @Override
    public String getMessage(){
        return msg;
    }
}

Sibling directory definition Captor class caught exception:

package com.base;

public class Captor {
    static int quotient(int x,int y)throws MyException{
        if(y<0){
            throw new MyException("Divisor cannot be negative");
        }
        return x/y;
    }

    public static void main(String[] args) {
        try {
            int res=quotient(3,-1);
        } catch (MyException e) {
            e.printStackTrace();
            System.out.println("getMessage result:"+e.getMessage());
        }catch (ArithmeticException e) {
            System.out.println("Divisor, cannot be 0.");
        }catch (Exception e) {
            System.out.println("Other exceptions occurred in the program.");
        }
    }
}


In the above code, if quotient(3,0) is called, the program jumps to the catch (arithmetexception E) code block for execution; If there are other exceptions, jump to the catch (Exception e) code block for execution. If catch (Exception e) is written in front of other exceptions, other exceptions will never be executed, because Exception is the parent of all Exception classes.

6. Abnormal operation

RuntimeException is an exception generated during program operation. Exception classes are defined in each package of the java class library. All these classes are subclasses of the throwable class. Throwable class derives two subclasses, exception and Error. The Error class and its subclasses are used to describe internal errors and resource exhaustion errors in the java operating system. Such errors are more serious. The exception class is called a non fatal class and can continue the execution of the program through capture processing. The exception class is divided into runtimeException and exceptions other than runtimeException according to the cause of the Error.

Common RuntimeException exceptions in java. These exceptions can be caught through try catch:

NullPointerException: null pointer exception
ArrayIndexOutOfBoundsException: array index out of bounds exception
ArithmeticException: arithmetic exception
ArrayStoreException: an exception thrown when the array contains incompatible values
IllegalArgumentException: illegal parameter exception
SecurityException: security exception
NegativeArraySizeException: array length is negative exception

Examples of runtime exceptions:

MyRunException.java

package com.base1;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

public class MyRunException extends RuntimeException{
    protected String errMsg;
    protected ErrorEnum errorEnum;
    public MyRunException(){super();}
    public MyRunException(ErrorEnum e){
        super(e.getDesc());
        this.errorEnum=e;
    }
    public MyRunException(ErrorEnum e,String errMsg){
        super(e.getDesc());
        this.errorEnum=e;
        this.errMsg=errMsg;
    }

    @Override
    public String toString(){
        return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }
}



interface MyErrorLev {
    //Logging level similar to python's logging
    String INFO="10";
    String WARNING="20";
    String ERROR="30";
    String FATAL="40";
}

enum ErrorEnum{
    NO_LOGIN_AUTH("101", "No_Login_Auth", "No login permission", MyErrorLev.ERROR),
    ILLEGAL_ARGUMENT("201","Illegal_Argument","invalid parameter", MyErrorLev.WARNING);
    private final String code;
    private final String name;
    private final String desc;
    private final String level;
    ErrorEnum(String code, String name, String desc, String level){
        this.code = code;
        this.name = name;
        this.desc = desc;
        this.level = level;
    }

    public String getLevel() {
        return level;
    }

    public String getCode() {
        return code;
    }

    public String getName() {
        return name;
    }

    public String getDesc() {
        return desc;
    }
}

RunTiExc.java

package com.base1;

public class RunTiExc {
    public static void main(String[] args) {
        myAssert(false,ErrorEnum.NO_LOGIN_AUTH);
    }
    public static void myAssert(boolean b,ErrorEnum e1){
        if(!b){
            throw new MyRunException(e1);
        }
    }
}

Exception in thread "main" MyRunException[errMsg=<null>,errorEnum=NO_LOGIN_AUTH,detailMessage=No login permission,cause=com.base1.MyRunException@330bedb4,stackTrace={},suppressedExceptions=[]]
	at com.base1.RunTiExc.myAssert(RunTiExc.java:9)
	at com.base1.RunTiExc.main(RunTiExc.java:5)

Tags: Java

Posted on Thu, 14 Oct 2021 16:15:03 -0400 by newbeee