The vast sea of millions, thank you for this second you see here. I hope my article is helpful to you!

May you keep your love and go to the mountains and seas in the coming days!

Java Exception Handling

😍 preface

I believe that you will be in the use of Java more or less there are some exceptions bug, then these exceptions from where?

Exceptions are some errors in a program, but not all errors are exceptions, and errors can sometimes be avoided. In Java, exceptions are a consistent mechanism that Java provides to recognize and respond to errors. Thus, the exception handling code in the program can be separated from the normal business code to ensure more elegant code and improve the robustness of the program.

😀1. What is an exception?

Abnormal means abnormal. And in life: doctors say you have an abnormality in a part of your body that is a little different from normal, and that part’s function will be affected. In the program it means:

  • Exceptions: Abnormal conditions that occur during the execution of a program and eventually cause the JVM to stop abnormally.

  • Exceptions are not syntax errors, syntax errors, compilations fail, no bytecode files are produced, you can’t run at all.

  • In object-oriented programming languages such as Java, an exception is itself a class, and to raise an exception is to create and throw an exception object.

  • Java has an exception handling mechanism for exceptions. When an exception occurs during a program’s execution, the program does not return any value. Instead, it throws an exception object that encapsulates the error message. This ensures more elegant code and improves program robustness.

    Why design exceptions? First, by introducing exceptions, we can separate the bad code from the normal code, which makes the code cleaner. Second, when something special happens, we can throw a check exception and tell the caller to handle it.

😄2. Abnormal system

  • Let’s look at the exception architecture first:

  • We can see the overall inheritance relationship of exception classes. Of course, not all exceptions are listed in the figure above, and many subclasses are not listed. Here are the more commonly used exception classes. Of course, users can also customize their own exception implementations.

📫 2.1 Throwable

All exceptions are inherited from the Throwable, which is the superclass of all errors and exceptions. Throwable contains a snapshot of the stack executed by its thread when it was created, and provides interfaces such as printStackTrace() to get information such as stack trace data.

  • The Throwable system contains two subclasses, Error and Exception, which are usually used to indicate that an Exception has occurred. Both are important subclasses of Java exception handling, each containing a large number of subclasses.

📪2.2 Error

  • Definition: Error class and its subclasses. An unhandled error in the program indicates a serious error in running the application. Most errors have nothing to do with what the code writer is doing, and instead represent problems with the JVM while the code is running.
  • The characteristics of: All compile-time errors and system errors are thrown through Error. These errors indicate that the failure occurred either in the virtual machine itself or when the virtual machine attempted to execute an application. Are oftenVirtual MachineError(VM running error). Occurs when the JVM no longer has the memory resources it needs to continue performing the operationOutOfMemoryError(No memory error), andStackOverflowError(stack overflow error), etc. When these exceptions occur, the JVM generally selectsThread terminates.
  • Note: These errors are unchecked exceptions, non-code errors, and cannot be checked. Because they are outside the control and processing power of the application, and most of them are not allowed to occur while the program is running. Even if an error does occur, a properly designed application should not, by nature, attempt to handle the exception it raises. Therefore, the application should not handle such errors when they occur.

📬2.3 Exception

Exception is another very important Exception subclass. Exceptions that can be caught and handled by the program itself. When such exceptions occur, we need to correct the code and fix the program. Exceptions fall into two categories: runtime and compile-time.

🔎 2.3.1Runtime exception

  • Definition: a RuntimeException class and its subclasses abnormalities, such as NullPointerException (null pointer exception), IndexOutOfBoundsException (subscript cross-border exception), said the JVM exceptions that may occur during operation.

  • Features: This type of exception is not checked by the Java compiler. It is usually caused by a program logic error. Such programs should logically avoid such exceptions as far as possible. When such an exception may occur in a program, it will be compiled even if it is not caught by a try-catch statement or thrown without a throws clause declaration. You can choose to capture processing in your program or not. If a runtime exception is generated, you need to modify the code to avoid it. For example, if a divisor of zero occurs, you need to code to avoid it!

  • Note: RuntimeException is automatically thrown and caught by the JVM (even if we didn’t write an exception catch statement at runtime!!). In most cases, the occurrence of such exceptions is a problem with the code itself, which should be solved logically and improved.

    So let’s take a look at what runtime exceptions look like, and what I want to say is, if you get an exception, don’t be nervous, just copy the simple class name of the exception into the API and look it up. And see what the abnormality is.

    As you can see, our program logic is faulty, so we have an arithmetic exception. We can just change int b to be equal to 10, or b not equal to 0.

    So we don’t have to worry about exceptions. You can start by looking at the name of the exception class, see what the exception is, see what the reason is, find out where our program went wrong and modify it to run normally.

  • So we didn’t handle anything, so when we get an exception, who handled the exception?

    Is the JVM’s default: the name, cause, location, etc., of the exception is printed to the console, but the program cannot continue to execute.

🔎2.3.2 Non-runtime Exceptions (Compile time exception)

  • Definition: Exception except for RuntimeException and its subclasses.

  • Features: This type of exception is checked by the Java compiler. If such an exception occurs in a program, it is an exception that must be handled from a program syntax perspective. For example, ClassNotFoundException (the specified class exception was not found) and IOException (the IO stream exception), which cannot pass compilation unless they are declared to throw or try-catch.

  • Note: In our programs, we usually do not customize the exception class, but use the exception class provided by the system. The exception must be handled manually by adding a catch statement to the code.

    As you can see from the comments, the createNewFile() method handles IOException, which in turn inherits from Exception and is a non-runtime Exception, so must handle exceptions.

    So if we have a compile-time exception, we will get an error at compile time, and we must handle this exception, otherwise the program will not compile.

📭2.4 Abnormal and undetected anomalies

Generally, Java exceptions (Throwable) are classified as checked exceptions and unchecked exceptions (unchecked exceptions).

💡2.4.1 Abnormal inspection

Exceptions that the compiler requires that must be handled.

  • Correct program in the running process, often easy to appear, in line with the expected abnormal situation. Once such exceptions occur, they must be handled in some way. With the Exception of RuntimeException and its subclasses, the Exception class and its subclasses are checked for non-runtime exceptions.

  • This exception is checked by the compiler, which means that when the compiler detects a possible exception somewhere in the application, it will prompt you to handle the exception — either using a try-catch or throwing with the throws keyword using the method signature, or the compiler fails.

💡2.4.2 Non-test exception

The compiler does not check and does not require exceptions that must be handled.

  • This type of exception is when an exception occurs in our program, even if we don’t have onetry-catchIt is captured and not usedthrowsThrow this exception, and the compilation will pass. This class includes runtime exceptions (RuntimeException and subclasses) and errors. When a RuntimeException occurs, it indicates that a programming error has occurred in the program, so you should find the bug modifier instead of catching a RuntimeException.

😮3. Exception handling mechanism (key)

In Java applications, the exception handling mechanism is: throw an exception, catch an exception.

🐁3.1 Java Exception Handling

  • In Java, once a method throws an Exception, the system automatically looks for an Exception Handler to handle the Exception according to the Exception object. It classifies different exceptions and provides a good interface.

  • In Java, each exception is an object that is an instance of the Throwable class or a subclass of it. When an exception occurs in a method, an exception object is thrown. This object contains the exception information, and the method calling this object can catch the exception and handle it.

  • Java exception handling involves five keywords: try, catch, finally, throw, and throws.

  • In Java applications, exception processing is divided into declare exception throws, and catch exception try, catch, and finally.

    Let me tell you more about it.

🐂3.2 Keywords of exception handling

  • Throw: Used to throw an exception.

  • Try: used for listening. The code to be listened on (code that might throw an exception) is placed inside the try block, and when an exception occurs within the try block, the exception is thrown.

  • Catch: Used to catch exceptions. Catch is used to catch exceptions that occur in a try block.

  • Finally: The finally block is always executed. It is primarily used to reclaim resources (such as database connections, network connections, and disk files) that are opened in the try block.

    A return or throw statement ina try or catch block is executed only after the finally block is completed. If a statement terminates a method, such as a return or throw, is used in the finally block, then execution is stopped.

  • Throws: Used in a method signature to declare exceptions that the method may throw.

Here to understand the keywords, the specific definition of the format and the use of the following introduction:

🐅3.3 Throwing an exception throw

  • So when do you use it?

    As a qualified programmer (and that’s me, isn’t it?), when we write programs, we have to consider the possibility that the program will go wrong.

    • For example, when defining a method, the method needs to accept parameters. Therefore, when calling a method to use the parameters received, the first need to determine the validity of the parameter data, if the data is illegal, we should tell the caller to pass in the valid data. You need to tell the caller by throwing an exception.
    • Or you can throw an exception when you feel you can’t resolve something that doesn’t need to be handled by the caller.
  • Throws an exception of type Throwable inside a method. Any Java code can throw an exception through a throw statement.

  • How do you throw an exception?

    1. Create an exception object. Encapsulate some prompts (you can write your own).

    2. The exception object needs to be told to the caller. How to tell? How do I pass this exception object to the caller? This is done with the keyword throw. Throw exception object.

      A throw is used within a method to throw an exception object, which is passed to the caller and ends execution of the current method.

  • Definition format:

    throw newException class name (parameter);Copy the code
  • Example:

    throw new NullPointerException("Arr array to be accessed does not exist");
      
    throw new ArrayIndexOutOfBoundsException("Index does not exist in array, out of range");
    Copy the code

    Next, use the program to demonstrate it:

    public class ThrowDemo {
        public static void main(String[] args) {
            // Create an array
            int[] arr = {2.4.52.2};
    
            // Find the corresponding element according to the index
            int index = 4;
            int element = getElement(arr, index);
    
            System.out.println(element);
            System.out.println("over");
        }
        /* * Find the corresponding element in the array */
        public static int getElement(int[] arr,int index){
            // Determine whether the index is out of bounds
            if(index<0 || index>arr.length-1) {/* The method cannot continue after the exception object is thrown. Execution of the current method is terminated and the exception is notified to the caller. This is where exceptions are needed to solve the problem. * /
                throw new ArrayIndexOutOfBoundsException("Dude, your index's out of bounds. Don't do that.");
            }
            int element = arr[index];
            returnelement; }}Copy the code

    After running, the output result is:

    Exception in thread "main"Java. Lang. ArrayIndexOutOfBoundsException: bro, you are the index of the crossing, don't do it at com. It. Test2. ThrowDemo. GetElement (ThrowDemo. Java:25)
    	at com.it.test2.ThrowDemo.main(ThrowDemo.java:10)
    Copy the code

    You can see that I’ve defined the index to be 4, but the array is only 4 in length. So an error will be reported.

    Note: So if there is a problem, we throw the problem description class, the exception, back to the caller of the method. The result is ArrayIndexOutOfBoundsException array index cross-border issues.

    So what about the caller? One is to capture processing, the other is to continue to declare the problem out, using throws declaration processing.

🐇3.4 Declaring an exception throws

If a method may throw an exception but does not have the ability to handle it, declare a throw exception with the throws clause on the method declaration. For example, when the car is running, it may have trouble. The car itself cannot deal with the trouble, so let the driver deal with it.

  • Declare an exception: Identify the problem and report it to the caller. If a compile-time exception is thrown by a throw inside a method without catch handling (which is explained later), then you must declare it through throws for the caller to handle.

    The keyword is applied to method declarations and is used to indicate that the current method does not handle exceptions, but rather to remind the method caller to handle exceptions (throw exceptions).

  • Definition format: The throws statement is used when a method is defined to declare the type of Exception to be thrown by the method. If an Exception type is thrown, the method is declared to throw all exceptions. Multiple exceptions can be separated by commas.

    Modifier return value type method name (parameter)throwsException class name1, the exception class name2... {}Copy the code

    Note: When a method throws an exception on the list of exceptions, the method does not handle exceptions of those types and their subclass types. Instead, the method that called the method handles them. After an exception is thrown to the caller using the throws keyword, if the caller does not want to handle the exception, the caller can continue to throw the exception upward, but eventually there must be a caller who can handle the exception. For example, if the car breaks down, the driver will not fix it, so he can only call a repair company to fix it.

  • To demonstrate:

    In general, throws and throws are usually paired, for example:

    public class ThrowsDemo {
        public static void main(String[] args) throws FileNotFoundException {
            readFile("a.txt");
        }
    
        // If a problem occurs while defining a function, report it to the caller. You can declare it by using the throws keyword on methods
        public static void readFile(String path) throws FileNotFoundException {
            if(! path.equals("a.txt")) {// if it is not a.txt file
                // I assume that if it is not a.tuck that the file does not exist is an error, that is, an exception throw
                throw new FileNotFoundException("File does not exist"); }}}Copy the code

    Throws is used to declare exception classes. If multiple exceptions may occur in this method, multiple exception classes can be written after throws, separated by commas.

    public class ThrowsDemo2 {
        public static void main(String[] args) throws IOException {
            readFile("a.txt");
        }
    
        // If the method may have more than one exception, write more than one exception class after throws, separated by commas
        // if a is a subclass of b, it can also be omitted
        private static void readFile(String path) throws FileNotFoundException, IOException {
            if(! path.equals("a.txt")) {// if it is not a.txt file
                // I assume that if it is not a.tuck that the file does not exist is an error, that is, an exception throw
                throw new FileNotFoundException("File does not exist");
            }
            if(! path.equals("b.txt")) {
                throw newIOException(); }}}Copy the code
  • Throws an exception rule:

    1. Unchecked Exception: Error, RuntimeException, or subclasses of them, you can declare exceptions to throw without using the throws keyword, and the compilation will pass without incident, but will be thrown by the system at run time.
    2. If a method may cause a Checked exception, use eithertry-catchStatement capture, either thrown with a throws clause declaration, or it results in a compilation error.
    3. Only when an exception is thrown must the method caller handle or rethrow it. If the method caller is unable to handle the exception, it should continue to throw it.
    4. The calling method must follow the handling and declaration rules for any searchable exception. If a method is overridden, exceptions that differ from the override method are not declared. Any exception declared must be a class or subclass of the exception declared by the overriding method.

🐉3.5 Catch exceptions try, finally, and catch exceptions

Try-catch, try-finally, try-catch-finally

Note: Catch statements can have one, more, or none. Finally, at most, must have a try.

So here you’re asking if there’s a separate try module, so I want to ask you, try is used to listen for exceptions, and if an exception occurs, who catches it? So no try appears alone. And the compilation doesn’t pass.

So like the try module, catch, finally, for example, cannot be used alone

  • The program usually does not report errors before running, but some unknown errors may occur after running. If you do not want to terminate the program due to exceptions, or if you do not want to throw it directly to the next level, you need to passtry-catchAnd other forms of exception capture, and then according to different exceptions to the corresponding processing.
  • Catch exceptions: In Java, exceptions are captured in specific statements that can be handled in a specified way.

Syntax for catching exceptions is as follows:

🔴3.5.1 Try-catch format:

try{write code that may fail}catch(Exception type e){Code for handling exceptions// Record logs/print exception information/continue to throw exceptions
}
Copy the code

Such as:

public class TryCatchDemo {
    public static void main(String[] args) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            // When an exception is raised, there must be a way to handle it. Either capture or declare.
            Date date = simpleDateFormat.parse("2020-10-06");
        } catch (ParseException e) {// What do I need to define in parentheses?
            // What exception is thrown in a try, and what exception type is defined in parentheses
            e.printStackTrace();// Record logs/print exception information/continue to throw exceptions
        }
        /* Public Date parse(String source) throws ParseException{} // Parse throws ParseException extends Exception {} */}}Copy the code

How to obtain exception information:

The Throwable class defines some viewing methods:

  • public String getMessage(): Obtains the description of the exception and the cause (The cause is displayed when the information is displayed to the user.
  • public String toString(): Obtains the type and description of the exception.
  • public void printStackTrace(): Prints exception trace stack information and prints it to the console.
  • Specifically, we can look at:
public class TryCathDemo2 {
 public static void main(String[] args) {
     SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
     try {
         // When an exception is raised, there must be a way to handle it. Either capture or declare.
         // Get the exception message.
         Date date = simpleDateFormat.parse("06 October 2020");
     } catch (ParseException e) {
         //public String getMessage(): Gets the description of the exception and the cause
         System.out.println(e.getMessage());//Unparseable date: "06 October 2020"
         System.out.println(e.toString());/ / Java. Text. A ParseException: Unparseable date: "in October 2020, 06"
         e.printStackTrace();// Output information and float red!!
         /* java.text.ParseException: Unparseable date: "In October 2020, 06" at Java. Text. The DateFormat, parse (DateFormat. Java: 366) at com. It. Test3. TryCathDemo2. Main (TryCathDemo2. Java: 13) * /}}}Copy the code

What if multiple exceptions are caught?

  1. Multiple exceptions are handled separately.
  2. Multiple exceptions are captured and processed multiple times.

Generally, we use a capture multiple processing mode, the format is as follows:

try{write code that may fail}catch(Exception type A e){WhentryIf A type A exception occurs incatchTo catch. Handle exception code// Record logs/print exception information/continue to throw exceptions
}catch(Exception type B e){WhentryIf a type B exception occurs incatchTo catch. Handle exception code// Record logs/print exception information/continue to throw exceptions
}
Copy the code

Such as:

public class TryCatchDemo3 {
    public static void main(String[] args) {
        //test();
        test2();
    }

    // Multiple exceptions are captured once and processed multiple times.
    public static void test2(a){
        int[] arr = {11.22.66.0};
        try {
            //System.out.println(arr[5]); // If this error occurs, the following code will not be executed
            System.out.println(arr[2]);
            System.out.println(arr[0] / arr[arr.length-1]);
        } catch (ArithmeticException e) {
             System.out.println("Divisor is not zero.");
        }catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index out of bounds");
        }catch(Exception e) { e.printStackTrace(); }}// Separate processing methods
    public static void test(a) {
        int a = 10;
        int b = 0;

        try {
            System.out.println(a / b);
        } catch (ArithmeticException e) {
            System.out.println("Divisor is not zero.");// The divisor is not 0
        }

        int[] arr = {1.2.3};
        try {
            System.out.println(arr[4]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index out of bounds");// Array subscript is out of bounds}}}Copy the code

Note: The method of handling the exceptions caught once and processed multiple times requires that the exceptions in multiple catches be different. In addition, if there is a relationship between the exceptions in multiple catches, the child exceptions should be handled in the catch above, and the parent exceptions should be handled in the catch below.

Such as:

🟠3.5.2 Try-finally format:

 try{   
  // The program code that is trying to run
}finally{   
  // When an exception occurs, the code is always executed
}  
Copy the code

Try-finally means that a piece of code will be executed regardless of its status.

Such as:

public class TryFinallyDemo {
    public static void main(String[] args) {
        int a = 10;
        int b = 0;
        try{
            System.out.println(a / b);
            System.out.println("Can you try?");
        }finally{
            System.out.println("Will you finally?");/ / will finally
        }

        System.out.println("Can you walk outside?");
        /* If there is no catch, only the finally statement will be issued and an exception will be raised. Will finally that the Exception in the thread "is the main" Java. Lang. ArithmeticException: / by zero at com.it.test3.TryFinallyDemo.main(TryFinallyDemo.java:8) */}}Copy the code

You can see that the program is not working properly, and the finally block is still being executed.

🟡3.5.3 Try-catch-finally format:

try {  
	// Program code that may be abnormal
} catch(Exception type A e){// Catch and dispose of the exception type A thrown by try
} finally {  
	// Block of statements that will be executed whether or not an exception occurs
} 
Copy the code

Similar to try-finally, this means that code in finally will be passed regardless of the execution.

When an exception occurs ina method, the code after the exception will not be executed. If some local resources have been obtained before and need to be released, the code that releases local resources needs to be called both at the normal end of the method and in the catch statement, which is cumbersome. Finally statements can solve this problem.

Such as:

public class TryCatchFinallyDemo {
    public static void main(String[] args) {
        test();
    }

    public static void test(a) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            //date = simpleDateFormat.parse("2020-10-06"); // The first run succeeded
            date  = simpleDateFormat.parse("06 October 2020");
        } catch (ParseException e) {
            e.printStackTrace();
        }finally{
            System.out.println("Finally here must be executed");
        }

        System.out.println("Would you walk out here?"+ date); }}Copy the code

The result of running successful code:

finallyThere must be an execution going out here, Tue Oct06 00:00:00 CST 2020
Copy the code

Results after running failed code:

java.text.ParseException: Unparseable date: "2020/10/06"
	at java.text.DateFormat.parse(DateFormat.java:366)
	at com.it.test3.TryCatchFinallyDemo.test(TryCatchFinallyDemo.java:19)
	at com.it.test3.TryCatchFinallyDemo.main(TryCatchFinallyDemo.java:12)
finallyIt's definitely going to be executed here is it going to go out herenull
Copy the code

As you can see, the code for the finally statement block executes regardless of failure.

  • In try-catch-finally, if a return is returned ina catch, will finally be executed?

    public class TryCatchFinallyDemo2 {
        public static void main(String[] args) {
            test();
        }
    
        public static void test(a) {
            int a = 10;
            try{
                System.out.println(a / 0);
            }catch(ArithmeticException e) {
                e.printStackTrace();
                return ;
            }finally {
                System.out.println("finally"); }}}Copy the code

    Running results:

    java.lang.ArithmeticException: / by zero
    	at com.it.test3.TryCatchFinallyDemo2.test(TryCatchFinallyDemo2.java:11)
    	at com.it.test3.TryCatchFinallyDemo2.main(TryCatchFinallyDemo2.java:5)
    finally
    Copy the code

    As you can see, finally is executed even if a return is returned ina catch.

    Is finally before or after a return?

    Let’s look at the following code, okay?

    public class TryCatchFinallyDemo2 {
        public static void main(String[] args) {
    // test();
            System.out.println(test2()); // Did I execute a try
            System.out.println(test3()); // Did I execute it
        }
    
        public static String test3(a) {
            String str = "";
            try {
                str = "try";
                System.out.println(10 / 0);
                return str;
            }catch(Exception e) {
                str = "catch";
                return str;
            }finally {
                str = "finally";
                System.out.println("Did I do it?"); }}public static String test2(a) {
            String str = "";
            try {
                str = "try";
                return str;
            }catch(Exception e) {
                str = "catch";
                return str;
            }finally {
                str = "finally";
                System.out.println("Did I do it?"); }}}Copy the code

    Running results:

    Did I follow throughtryDid I follow throughcatch
    Copy the code

    You can see here that finally executes whether or not it is an exception, but the code executes before the return. But why isn’t the string finally returned? Let’s think about it:

    • If we look at test2(), the program executes the try statement block and assigns the variable STR to “try”. Since no exception is found, it executes the finally statement block and assigns the variable STR to “finally”. Then return STR. Finally, the value of STR is “finally”. The program result should say finally, but the actual result is “try”.

    • In fact, in the return block of the try statement, when we get to return STR, instead of a return STR, we get a return “try”, and we have this put back path.

      The reference variable returned by return (STR is the reference type) is not the reference variable STR defined outside of the try statement. Instead, the system redefines a local reference str2 and returns the value of the reference str2, which is the “try” string.

      But at this point, it finds that finally is followed by STR = “finally”; System.out.println(” Did I execute it? “); Return “try”. After the return path is formed, the return reference for return is not the variable STR, but the value “try” string referenced by str2.

    Is there a certain understanding of this phenomenon. Hey, hey, here we switch again:

    public class TryCatchFinallyDemo2 {
        public static void main(String[] args) {
    // test();
    // System.out.println(test2()); // try
    // System.out.println(test3()); // catch
            System.out.println(test4()); 
    
        }
    
        public static String test4(a) {
            String str = "";
            try {
                str = "try";
                return str;
            }catch(Exception e) {
                str = "catch";
                return str;
            }finally {
                str = "finally";
                returnstr; }}}Copy the code

    So let’s guess here, what is the result?

    Run result: finally

    • We find that the return statement in the try statement is ignored. The JVM may think that having two return statements ina method doesn’t make much sense, so the return statement in try is ignored. The return statement in finally is used to form a new return path"Finally"A string.

    Look again: Do we know that the finally statement must be executed, but is there a way to make it not?

    Now that I say it, there is.

    public class TryCatchFinallyDemo3 {
        public static void main(String[] args) {
            try{
                System.out.println(10 / 0);
            }catch(Exception e) {
                e.printStackTrace();
                System.exit(0);
            }finally {
                System.out.println("Finally, did I execute it?"); }}}Copy the code

    Execution Result:

    java.lang.ArithmeticException: / by zero
    	at com.it.test3.TryCatchFinallyDemo3.main(TryCatchFinallyDemo3.java:6)
    Copy the code

    It can be found:

    Finally is not executed when the associated method exiting the JVM is called only ina try or catch, otherwise it will always be executed.

🔵 3.5.4 summary

  1. Try block: Used to catch exceptions. This may be followed by zero or more catch blocks, or if there is no catch block, a finally block must follow.
  2. Catch block: Used to handle exceptions caught by a try.
  3. Finally block: Statements ina finally block are executed whether or not exceptions are caught or handled. When a return statement is encountered ina try or catch block, the finally block is executed before the method returns. A finally block is not executed in four special cases:
    • An exception occurred in the finally statement block.
    • I used it in the previous codeSystem.exit()Exit the program.
    • The thread on which the program resides dies.
    • Close the CPU.

🐍3.6 How to Select an exception type

You can use the following figure to choose whether to catch, declare, or throw an exception

The rules we should follow in everyday exception handling code are:

  • Don’t catch exceptions like Exception, catch specific exceptions like Exception, it’s easy to troubleshoot problems, and it’s less likely that other people will scold you when they take over your code.

  • Don’t eat anything raw. This is something to pay special attention to in exception handling. If we don’t throw the exception, or if we don’t log it, the program may end up in an uncontrollable fashion later on. Sometimes you need to debug code online.

😛4 JDK1.7 About new exception features

📤 4.1 try – with – resources

There are many resources in the Java class library that need to be closed by the close method. Such as InputStream, OutputStream, etc. As a developer, you often ignore the resource shutdown method, resulting in memory leaks. Of course not me!

Prior to JDK1.7, try-catch-finally statements were the best way to ensure that a resource would be closed, even if it was an exception or a return.

  • Let’s take a look at how we closed the resource earlier:

    public static String readFile(String path) {
        BufferedReader br = null;
    
        try {
            br = new BufferedReader(new FileReader(path));
            return br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {// The resource must be closed here
            if(br ! =null) {
                try {
                    br.close();
                } catch(IOException e) { e.printStackTrace(); }}return null; }}Copy the code

    Do we have to manually close the resource in the finally statement block, otherwise it will leak

  • In JDK1.7 and later:

    The try-with-resources statement was introduced in JDK1.7.

    • try-with-resourcesA statement is a try statement that declares one or more resources.try-with-resourcesThe statement ensures that at the end of the statement every resource is closed, as long as objects implementing either the AutoCloseable or Closeable interfaces are availabletry-with-resourcesTo implement exception handling and close resources.
    • In fact, this is also done at compile timetry-catch-finallyStatements.

    Let’s see how it works:

    Format:

    tryCreate a stream object statement, if multiple, use'; 'Separated) {// Read and write data
    } catch (IOException e) {
    	e.printStackTrace();
    }
    Copy the code

    Presentation:

    /** * try-with-resources can be used after JDK1.7 without having to manually close resources in the finally block */
    public class TryWithResourcesDemo {
        public static String readLineFormFile(String path) {
            try (BufferedReader br = new BufferedReader(new FileReader(path))) {
                return br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null; }}Copy the code
  • A comparison of the two:

    • Code refinement. Before JDK1.7, finally blocks were available. If you use some frameworks, you might hand them over to a framework like Spring. JDK1.7 and later will automatically close the resource used by br.readline () after executing the try block if the resource class implements AutoCloseable or Closeable, regardless of whether br.readline () throws an exception.

    • The code is more complete. In many cases where a resource leak occurs, the developer does not or does not shut down the resource properly. With the try-with-resources approach adopted after JDK1.7, it is possible to hand off resources that are not directly related to the business implementation to the JVM. Part of the code risk that may occur during development is eliminated.

    • In the case of the readLineFormFile method, if calls to both the readLine() and close() methods throw exceptions, the latter exception is disallowed in order to preserve the first.

📥4.2 Catch multiple exceptions and throw new ones

  • Before JDK1.7, catch multiple exceptions looked like this:

    try{write code that may fail}catch(Exception type A e){WhentryIf A type A exception occurs incatchTo catch. Exception handling code}catch(Exception type B e){WhentryIf a type B exception occurs incatchTo catch. Exception handling code}Copy the code
  • JDK1.7 and later can do this:

    try{write code that may fail}catch(exception type A | exception type B e) {exception handling code}Copy the code

    But, you can only define it this way if it’s of the same type.

😜5 User-defined exceptions

🛳️5.1 Why custom exception classes are needed:

We talked about the different exception classes in Java, which represent a specific exception, so in development, when Java built-in exceptions do not clearly describe the exception, you need to create your own exception. For example, negative age, negative test scores.

What is a custom exception class?

Define your own exception classes according to your own business exception situations during development. For example: login system, age can be negative, can not need to define a login exception class.

⛴️5.2 How can I Define a Custom exception Class

  1. Custom a compile-time exception: custom class and inherit fromjava.lang.Exception
  2. Customize a runtime exception class: Custom class and inherit fromjava.lang.RuntimeException
  • Generally, defining an exception class requires two constructors: a no-parameter constructor and a constructor with detailed description information
public class MyException extends Exception {
    public MyException(a){}public MyException(String message){
        super(message); }}Copy the code

🛥️5.3 Examples of user-defined exceptions

Requirement: We simulate login operation, if the user name already exists, throw an exception and prompt: pro, the user name is already registered. I believe that we often see it.

  1. Start by defining a LoginException class:

    /** * login exception class */
    public class LoginException extends Exception {
        public LoginException(a) {}public LoginException(String message) {
            super(message); }}Copy the code
  2. Simulate login operation, using array to simulate the data stored in the database, and provide the method to determine whether the current registered account exists.

    public class LoginTest {
        // An account already exists in the simulated database
        private static String[] names = {"hello"."world"."fish"};
       
        public static void main(String[] args) {     
            // Call the method
            try{
                // Possible exception code
                checkUsername("fish");
                System.out.println("Registration successful");// If there is no exception, the registration is successful
            } catch(LoginException e) {
                // Handle exceptionse.printStackTrace(); }}// Check whether the current registered account exists
        // This is a compile-time exception and is intended to be handled by the caller
        public static boolean checkUsername(String uname) throws LoginException {
            for (String name : names) {
                if(name.equals(uname)){// Throw a login exception if the name is inside
                    throw new LoginException("Kiss"+name+"Already registered!"); }}return true; }}Copy the code

    Result: The registration is successful.

🌸6. End loose flowers

Believe that everyone accepts the exception that a system have a certain understanding, in our actual application, generally to have abnormal place some effective processing, such as in the case of if abnormal, may return to the friendly interface or friendly message to the user, always can’t put some exception information to the user, the user experience is quite bad drop! So exception handling is necessary!

Let’s refuel together, too! I am not just, if there is any missing, wrong place, also welcome you to criticize in the comments of talent leaders! Of course, if this article is sure to help you a little, please kindly and lovely talent leaders to give a thumb-up, favorites, one key three even, thank you very much!

Here, the world is closed for today, good night! Although this article is over, I am still here, never finished. I will try to keep writing articles. The coming days are long, why fear the car yao ma slow!

Thank you all for seeing this! May you live up to your youth and have no regrets!