1 (Java advanced features) exception handling

Keywords: Java

**Bullshit: * * Hello, everyone. Welcome to this article. I'm a beginner of java. Ready to find a job after February 7, 22, now take a 70 day sprint note. Overall notes from advanced java features to microservice architecture (which is my route). From today on, I want to be self disciplined (I hope you like it). Welcome to discuss and study together. I'm a beginner shivering

All my notes here are from online videos: Shang Silicon Valley, dark horse, etc. these two address videos are very awesome

silicon valley

https://www.bilibili.com/read/cv5216534?spm_id_from=333.999.0.0

dark horse

https://www.bilibili.com/read/cv9965357?spm_id_from=333.999.0.0

This one comes from the advanced part of 30 days java in Silicon Valley

Silicon Valley, dark horse's notes can be asked for from me if you need them

exception handling

What is an exception

When we write java code, exceptions often occur when running. This time the program will stop.

Of course, sometimes even if we report an error, we don't want the program to stop, but we can continue to execute.

In the Java language, abnormal conditions occurring during program execution are called "exceptions".

(syntax and logic errors during development are not exceptions)

The problems caused by logic generally do not affect the program interrupt, but the results are different from what we think.

java program exception classification

Error

Serious problems that cannot be solved by the Java virtual machine. JVM system internal error, resource exhaustion and other serious conditions.

For example:

public class ErrorTest {
    public static void main(String[] args) {
    
//        An exception reached by overflowing the stack
//Exception in thread "main" java.lang.StackOverflowError
        main(args);
        
    }
}

Exception

Other general problems caused by programming errors or accidental external factors can be handled with targeted code.

For example:

  1. Null pointer access
  2. An attempt was made to read a file that does not exist
  3. Network connection interrupted
  4. Array subscript out of bounds

exception classification

Compilation exception (checked exception)

The best way to catch errors is to see them through tools such as IDEA during compilation and before running

That can handle exceptions

Runtime exception

Some errors occur only at runtime.

Divisor is 0, array subscript is out of bounds, etc

Exception type diagram

Throwable: the parent class of the exception. There are many divisions below

Error: the error belongs to JVM exception, which is hard to handle (I don't understand 55 here)

Exception: normal exceptions we often encounter. It is divided into checked exceptions and runtime exceptions

The videos in Silicon Valley are really powerful and worthy of recommendation

Treatment method

We generally use two methods for exceptions

  1. try-catch-finally
  2. throws

Try-catch-finally

grammar

Example

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

//        Because the array length is 5, the subscript starts from 0.
//        So I'm sure there will be runtime exceptions here
        //Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5

        int [] intArr = new int[5];

        try {
            System.out.println("Run the parts where exceptions may occur");
            //Exceptions may occur in this paragraph.
            intArr[5] = 1;
            System.out.println("After running the part with possible exceptions");
        } catch (ArrayIndexOutOfBoundsException e){
            System.out.println("Catch exception message"+e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Exception handling completed------------");

    }
}

Analysis according to the results

First of all, we know that there must be exceptions in the code in try (we wrote it ourselves)

At this time, we write a print statement on it, because when an exception occurs in the try, the try will not continue to execute

The exception type matching of catch will be performed

Note: the catch condition here is similar to the match in switch. If you select more than one parent class exception, it cannot appear above the child class exception, because the child class will not be considered after the child class exception. The subclass will lose the meaning of writing, and the catch () module will also have a check exception

Discovery: Although the above still reported an exception, the program did not terminate, but continued to execute

There are two common methods for exception classes

As we can see from the above code, there are also methods in the exception class of catch that can be called

methoddescribe
getMessage()Return exception information, String return value
printStackTrace()Printing stack information will print a lot of information in the console, which is the same as the previous error style, but will not affect subsequent execution

finally

finally: it is a module that will be executed in the end no matter what

No matter whether there is a return in: try or not, catch: another exception occurs or the return is performed. Finally, the module will execute

finally, the role of

We often need to close some resources during IO operation or JDBC operation. Avoid waste of resources

Therefore, we can use finally to close resources when there are exceptions in the program. Other operations

Throws (declaration throws an exception)

If a method (when the statement in is executed) may generate some kind of exception, but it is not sure how to handle this exception,

This method should explicitly declare that exceptions are thrown, indicating that the method will not handle these exceptions,

The caller of the method is responsible for processing.

Example

Display through examples and read the content through the note number

public class TrowsExceptionTest {

    //6. Of course, main () can continue to throw exceptions and hand them over to the jvm for processing
//    It's best to handle it yourself in the main method
    public static void main(String[] args) throws Exception {
        TrowsExceptionTest tet = new TrowsExceptionTest();
        tet.TrowseTestTwo();

    }
    
    public void TrowseTestTwo() throws InterruptedException,Exception{
//3. When calling the One method, it is found that the Checked exception also occurs
//        4. Because one didn't handle the exception, the exception was still there, but it was handed over to the caller for processing
//        5. So two chooses to continue throwing
        TrowsTestOne();
    }

    public void TrowsTestOne()throws InterruptedException,Exception{

        //1. Thread hibernation is a checked exception. I did not use try catch to handle it here
//        2. Instead, throw the exception
        Thread.sleep(1000);
    }


}

be careful

The exception type thrown by the caller cannot be less than the exception of the calling method. (the checked prompt will appear)

Try catch finally compare rows

Try catch, you can perform more operations and use it more abundantly

Silicon Valley recommendations

Throw (throw exception manually)

During execution, we create an exception ourselves. When running here, no exception handling will be carried out, and a checked exception or runtime exception will be reported

It depends on what type of exception is thrown manually

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

//        Exception handling through try catch
        try {
            ThrowTestOne(-2);
        } catch (Exception e) {
//            Print abnormal information
            System.out.println(e.getMessage());
        }

    }


//    Generally, judge whether to throw an exception. The exception thrown also needs to be handled
    public static void ThrowTestOne(int num){

//        If the parameter num of this method is less than 0, a runtime exception is thrown
        if(num<0){
            throw new RuntimeException("num Less than 0");
        }
    }

}

Custom exception class

Generally, user-defined exception classes are subclasses of RuntimeException.

Custom exception classes usually require writing several overloaded constructors.

The user-defined exception needs to provide serialVersionUID for unique representation

Custom exceptions are thrown through throw.

The most important thing for custom exceptions is the name of the exception class. When an exception occurs, you can judge the exception type according to the name.

Example

Create custom exception class

Using custom exception classes

Normal call

Posted by Dave Liebman on Sat, 20 Nov 2021 17:00:04 -0800