Exception s, errors and exceptions, catching and throwing exceptions, custom exceptions

Posted by jimbob on Sun, 16 Jan 2022 13:17:07 +0100

What is an exception
  • In actual work, the situation encountered can not be very perfect. For example, for a module you write, the user input does not necessarily meet your requirements. If your program wants to open a file, the file may not exist or the file format is wrong. You want to read the data in the database, and the data may be empty. Our program is running. The memory or hard disk may be full. wait.
  • During the operation of software programs, it is very likely to encounter these abnormal problems just mentioned, which we call exceptions. English is: Exception, which means Exception. These exceptions, or exceptions, how to make the program we write deal with reasonably. Without the program crashing.
  • Exceptions refer to unexpected conditions during program operation, such as file missing, network connection failure, illegal parameters, etc.
  • The exception occurs during the program running, which affects the normal program execution process.
Simple classification
  • To understand how Java exception handling works, you need to master the following three types of exceptions:
  • Inspection abnormality:
    • The most representative checking exception is the exception caused by user errors or problems, which can not be foreseen by programmers. For example, when you want to open a nonexistent file, an exception occurs. These exceptions cannot be simply ignored at compile time.
  • Runtime exception:
    • Runtime exceptions are exceptions that can be avoided by programmers. In contrast to checking exceptions, runtime exceptions can be ignored at compile time.
  • error:
    • Errors are not exceptions, but problems out of programmer control. Errors are usually ignored in code. For example, when the stack overflows, an error occurs, and they cannot be checked during compilation.
Exception architecture
  • Java treats exceptions as objects and defines a base class java Lang. throwable is the superclass of all exceptions.
  • Many Exception classes have been defined in the Java API. These Exception classes are divided into two categories: Error and Exception.
Error
  • The Error class object is generated and thrown by the Java virtual machine. Most errors have nothing to do with the operation performed by the coder.
  • Java virtual machine running error. OutOfMemoryError will appear when the JVM no longer has the memory resources required to continue the operation. When these exceptions occur, the Java virtual machine (JVM) generally selects thread termination.
  • In addition, when the virtual machine attempts to execute the application, such as class definition error (NoClassDefFoundError) and link error (LinkageError). These errors are not traceable because they are outside the control and processing power of the application, and most of them are not allowed when the program is running.
Exception (exceptions other than runtime exceptions can be called non runtime exceptions)
  • There is an important subclass runtimeException (runtime Exception) in the Exception branch
    • Arraylndexofboundsexception (array subscript out of bounds)
    • NullPointerException (null pointer exception)
    • Arithmeticexception (arithmetic exception)
    • Missingresourceexception (missing resource)
    • Classnotfoundexception (class not found) and other exceptions. These exceptions are not checked. The program can choose to capture and handle them or not.
  • These exceptions are generally caused by program logic errors. The program should avoid such exceptions as far as possible from a logical point of view (these exceptions are generally caused by program developers).
  • Difference between Error and Exception:
    • Error is usually a catastrophic and fatal error that cannot be controlled and handled by the program. When these exceptions occur, the Java virtual machine (JVM) generally chooses to terminate the thread.
    • Exception s can usually be handled by the program, and these exceptions should be handled as much as possible in the program.
Exception handling mechanism
  • Throw exception
  • Catch exception
  • Five keywords for exception handling
    • try,catch,finally,throw,throws

First look at the example:

  • When the divisor is "0", an error will be reported and an exception will be thrown.

  • Use keywords to catch exceptions.

  • try and catch key areas are necessary, and finally is optional. However, operations that need to be closed when processing IO stream operations or resource related operations need to be placed in finally.

  • Suppose there are other exceptions in the current sample

    • Add a() and b() methods to the current class, calling each other. A stack overflow exception occurs. See how to catch non corresponding exceptions.
package com.landray.exception;

public class Test01 {
    public static void main(String[] args) {
       int a = 1;
       int b = 0;
       try {
           //Monitoring area. In this code block, code exceptions will be caught
           new Test01().a();
       }catch (ArithmeticException e){//Catch exception (ArithmeticException)
            //If this exception occurs in the try, the code in the catch code block will be executed
           System.out.println("Program exception, variable b Cannot be 0");
       }finally{//Deal with the aftermath
           //The program will execute the code whether there is an exception or not.
           System.out.println("finally");
       }
    }
    
    public  void a (){
        b();
    }

    public  void b (){
        a();
    }
}

The execution effect is:
Obviously, this exception cannot be caught.

You can see from the running results that no matter what exception occurs, this finally will be executed. Deal with the aftermath and report the error only after it is handled.

When the corresponding exception cannot be captured, try to capture the largest exception, which can be captured. As shown below:

  • If there are many exceptions in the code, can you catch multiple exceptions?
    It can catch multiple exceptions, which is the same logical relationship as if and else. Expand the captured exceptions step by step. The largest exception needs to be written at the bottom, not at the top, because if the largest exception is not captured as soon as it is opened, the following exception capture will not be performed. Logic such as if and else if will only execute one in the end. (catch exceptions from small to large)
package com.landray.exception;

public class Test02 {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        try {
            System.out.println(a / b);
        } catch (Exception e) {
            //You can add your own logical judgment before printing exceptions
            System.exit(1);//For example, manually end the program here
            e.printStackTrace();//Print wrong stack information
        } finally {

        }
    }
}

When writing code, if you know that it is obvious, errors may occur. For example, if the user is asked to enter a divisor, the user may enter "0", so that he can judge and actively throw an exception.

throws

package com.landray.exception;

public class Test01 {
    public static void main(String[] args) {
        new Test01().test(1, 0);
    }

    //If the exception cannot be handled in this method, you need to throw the exception out to a higher level. (exception thrown on method) throws
    public void test(int a, int b) throws ArithmeticException {//throws (method)
        if (b == 0) {//throw (in method)
            throw new ArithmeticException();//Actively throw exceptions, which are generally used in methods.
        }
    }
}

When an exception is thrown, when it is called, it needs to be captured normally. If you don't use try and catch, the program stops when you encounter this error.

package com.landray.exception;

public class Test01 {
    public static void main(String[] args) {
        try {
            new Test01().test(1, 0);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        }
    }

    //If the exception cannot be handled in this method, you need to throw the exception out to a higher level. (exception thrown on method) throws
    public void test(int a, int b) throws ArithmeticException {//throws (method)
        if (b == 0) {//throw (in method)
            throw new ArithmeticException();//Actively throw exceptions, which are generally used in methods.
        }
    }
}

Custom exception
  • Using Java's built-in Exception class can describe most exceptions during programming. In addition, users can customize exceptions. You can customize the Exception class by inheriting the Exception class.
  • Using custom exception classes in programs can be roughly divided into the following steps:
    • Create a custom exception class.
    • Throw an exception object through the throw keyword in the method.
    • If an exception is handled in the method that currently throws an exception, you can use the try catch statement to catch and handle it; Otherwise, use the throws keyword at the method declaration to indicate the exception to be thrown to the method caller, and continue with the next operation.
    • Catch and handle exceptions in the caller of the exception method.
  • Custom exception example:
    1. First write a custom exception class:
    (an exception is thrown when the input number is greater than 10)
package com.landray.exception;

//Custom exception
public class MyException extends Exception {

    //Transfer number > 10
    private int detail;

    //Constructor (alt+insert)
    /*public MyException(String message) {
        super(message);
    }*/
    //After modification
    public MyException(int a) {
        this.detail = a;
    }

    //How to make others print out error messages, you need to write a toString method
    //Abnormal print information (alt+insert)
    @Override
    public String toString() {
        return "MyException{" +
                "detail=" + detail +
                '}';
    }
}

2. Write a test exception class:
The error report says that an unknown exception will appear here. The two solutions are:
1. Try catch in the current method
2. Throw the exception throws (thows) to a higher level for the caller of this method to catch
If you capture it here, you don't need to capture it outside. If you throw it here, you need to capture it outside (where the method is called).

  • Because in the above methods, you have selected to let throw and let the caller catch, you will be reminded of exceptions when writing methods to call. (so I'll capture it here)
package com.landray.exception;

public class ExceptionTest {
    //There may be abnormal methods
    static void test(int a) throws MyException {  //Select throw, and the caller captures it
        System.out.println("The parameters passed are:" + a);
        if (a > 10) {
            throw new MyException(a);
        }
        System.out.println("OK");
    }

    public static void main(String[] args) {
        try {
            test(1);
        } catch (MyException e) {
        	//You can add some code blocks to handle exceptions
        	if(){
        	}else{
        	}
            System.out.println("MyException=>" + e);
        }
    }
}

Experience summary in practical application
  • When dealing with runtime exceptions, logic is used to reasonably avoid and assist in try catch processing.
  • After multiple catch blocks, you can add a catch (Exception) to handle exceptions that may be missed.
  • For uncertain code, you can also add try catch to handle potential exceptions.
  • Try to handle exceptions, and never simply call printStackTrace() to print out.
  • How to handle exceptions should be determined according to different business requirements and exception types.
  • Try to add finally statement blocks to release the occupied resources.