Java ① (BV12J41137hu): day 12

Exception:

exception refers to various 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 of exceptions:

① Checking exception: the most representative checking exception is the exception caused by user errors or problems, which cannot be foreseen by programmers. For example, when you want to open a nonexistent file, exceptions occur. These exceptions cannot be simply ignored at compile time.

② Runtime exceptions: runtime exceptions are exceptions that may be avoided by programmers. Contrary to checking exceptions, runtime exceptions can be ignored at compile time.

③ ERROR: an ERROR is not an exception, but a problem out of the programmer's 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 as 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 a reference, 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 referenced program, and most of them are not allowed when the program is running.

Exception:

There is an important subclass runtimeyexception (runtime Exception) in the Exception branch

① ArrayIndexOutOfBoundsException (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 much as possible from a logical point of view.

Difference between Error and Exception:

Error is usually a catastrophic fatal error that cannot be controlled and handled by the program. When these exceptions occur, the Java virtual machine (JVM) will generally choose 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 an exception and catch an exception.

There are five keywords for exception handling: try,catch,finally,throw,throws.

For example:

public class Demo02 {
    public static void main(String[] args) {

        int a = 1;
        int b = 0;

        try{ //try monitoring area
            System.out.println(a/b);
        }catch (ArithmeticException e){ //Catch catch exception
            System.out.println("Program exception, variable b Cannot be 0");
        }finally {  //Deal with the aftermath
            System.out.println("finally");
        }

        //Finally, you can not finally
        //However, assuming that IO streams or resources need to be closed, they can be closed in finally
    }
}

Output:

For example:  

public class Demo03 {
    public static void main(String[] args) {

        int a = 0;
        int b = 0;

        //Suppose you want to catch multiple exceptions: from small to large
        //Multiple catch es, from top to bottom, gradually expand or disjoint each other
        //Ctrl Alt + t shortcut
        try{  //try monitoring area
            if (b==0){  //Actively throw throws exceptions, which are generally used in methods
                throw new ArithmeticException();
            }
            System.out.println(a/b);
        }catch (Error e){  //Catch (the type of exception you want to catch)
            System.out.println("Error");
        }catch (Exception e){
            System.out.println("Exception");
        }catch (Throwable t){
            System.out.println("Throwable");
        }finally {  //Deal with the aftermath
            System.out.println("finally");
        }
    }
    public void a(){
        b();
    }
    public void b(){
        a();
    }
}

For example:

public class Demo04{
    public static void main(String[] args) {

        try{
            new Demo04().test(1,0);
        }catch (ArithmeticException e){
            e.printStackTrace();
        }
    }

    //Suppose this method cannot handle this exception, and an exception is thrown on the method
    public void test(int a,int b) throws ArithmeticException{
        if(b==0){  //throw throws
            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 Exeception 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 class
public class MyException extends Exception{
    
    //Transfer number > 10
    private int detail1;
    
    public MyException(int a){
        this.detail1 = a;
    }
    
    //toString: abnormal print information
    @Override
    public String toString(){
        return "MyException{" + detail1 +'}';
    }
}
public class Test {

    //There may be abnormal methods
    static void test(int a)throws MyException{
        System.out.println("The parameters passed are:"+a);

        if (a>10){
            throw new MyException(a); //Throw
        }
        System.out.println("OK");
    }

    public static void main(String[] args) {
        try {
            test(1);
        }catch (MyException e){
            //Add some code to handle exceptions
            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 a finally statement to release the occupied resources.

Tags: Java

Posted on Fri, 12 Nov 2021 08:13:51 -0500 by dstockto