Java Exception Handling (Part 1)

  Today we're going to talk about a little goblin in Java, the exception.

What is an exception? What is exception handling?

  Exception, as the name implies, is abnormal, (escape), is an unexpected thing that occurs when a Java program is running, it prevents the program from executing normally according to the programmer's expectations.

  Exception handling, it should be said that the exception handling mechanism is the magic weapon specially used to subdue this little goblin. The exception handling mechanism in Java allows the program to deal with the exception in a targeted manner according to the pre-set exception handling logic of the code when an exception occurs, so that the program can return to normal as much as possible and continue to execute, and the code is kept clear.

  In short, Java exception handling is what allows us to proactively respond to possible exceptions and handle them in a mellow manner.

  Let's take a look at a small chestnut first to see what the exception in java looks like.

public class Test {
    public static void main(String args[]){
        int i = 0 / 0;
        System.out.println("i = " + i);
    }
}

  

  Don't panic, don't panic when you see the red prompt, just want to close the IDE, come, grab my hand, and show you the true face of "abnormal", the annoying little goblin (funny).

  The code uses 0 as the denominator, so the program will have an arithmetic exception. After an exception is thrown, if there is no processing, the program will be terminated by default, so the following print content is not output. In the exception content, it is stated that the exception type is: java.lang.ArithmeticException, which is an arithmetic exception, followed by the exception reason: / by zero, which means that the reason for the exception is that 0 is used as the denominator, and it is followed by There is stack information, indicating that the location of the exception thrown is in the com.frank.chapter16.main.Test.main package, the 11th line of the Test class (if the number of lines is different from what you think, don't care, because There are some non-descriptive instructions before my code starts), because there is only one method call, there is no long stack information, and it looks very concise.

  So you see, in fact, the exception is not so terrible, it not only gives the reason for the exception, but also tells you which line the bug is in, so make good use of it, it can help you write bugs that are more difficult to find, bah, say Wrong, can help you find bugs more easily (manually funny).

  What if you don't want the program to end when an exception is thrown, but want it to keep running? Then catch it.

How to use exception handling

  Let's change the chestnut above:

public class Test {
    public static void main(String args[]){
        try{
            int i = 0 / 0;
        }catch (Exception e){
            System.out.println("好像发生异常了,但是我不管,我还要继续运行");
        }
        System.out.println("运行完毕!");
    }
}

  The output is as follows:

It seems that an exception has occurred, but I don't care, I will continue to run
Done!

  OK, strong, now the program continues to run even if an exception is thrown. An anomaly is like a beast, but once you capture it and tame it, you can use it and do whatever you want.

  try...catch... is a commonly used exception handling combination. If an exception occurs in the try statement block, if the exception is caught, it will jump directly to the catch statement block and execute the code in the catch statement. Like the chestnut above, because the Exception class is caught, it can also be caught when its subclass exception java.lang.ArithmeticException is thrown. The structural hierarchy of the Exception class will be introduced in detail later.

  There is another way of collocation, that is try...catch...finally. The finally block is much stronger than the catch. As mentioned earlier, the catch block must catch a specific Exception before executing the code inside. If the catch is an ArithmeticException but a null pointer exception is thrown, it will not be caught and the exception will escape. At this time, the advantages of finally are shown, no matter what kind of exception is thrown, and whether or not an exception is thrown, the code in finally will be executed. So the general usage is to release those resources that need to be released in the finally block, such as socket connections, closing io streams, closing database connections, and so on. That is to say, it is generally necessary to clean up the mess thrown in try in finally.

  Of course, the combination of try...finally is also ok. It should be noted that when an exception occurs in the try statement, the code after the exception will not be executed, but will jump to the corresponding catch or finally go in.

public class Test {
    public static void main(String args[]){
        try{
            int i = 0 / 0;
        }catch (NullPointerException e) {
            System.out.println("这里捕获空指针异常");
        }catch (ArithmeticException e){
            System.out.println("这里捕获算术异常");
        }finally {
            System.out.println("这里是finally");
        }
        System.out.println("运行完毕!");
    }
}

  The output is as follows:

Arithmetic exception is caught here
here is finally
Done!

  In the above code, multiple catch statement blocks can be used at the same time. The first catch statement block catches the null pointer exception, but because it throws an arithmetic exception, it is not caught, but is caught by the second catch block. caught, so the code in the second catch block executes. Exception matching is performed in order from top to bottom, and the code block in finally is executed at the end. Regarding try...catch...finally, there is also an interesting return question. If there are returns in all three statement blocks, what will be the final return result? Here is a detailed description, http://www.cnblogs.com/mfrank/p/7895660.html If you are interested, you can take a look.

  In most cases, the code in finally will be executed. There is only one case in which the code in finally will not be executed, that is, the virtual machine is terminated in the try block (such as: using System. exit(0); ).

  Regarding exceptions, there is another keyword that needs to be introduced, that is throw. Using throw can actively throw an exception. Seeing this, you may be confused and take the initiative to throw it out? ? ? Don't think there are not enough exceptions, don't think it's a big deal to join in the fun? ? Don't worry, don't worry, there must be some misunderstanding in the middle, put down the knife, and have something to say.

  The throw keyword is indeed used to throw exceptions, you can use it like this:

public class Test {
    public static void main(String args[]){
        try{
            throw new NullPointerException("听说你很闲,给你抛个异常。");
        }catch (NullPointerException e) {
            System.out.println("这里捕获空指针异常,提示内容:" + e.getMessage());
            e.printStackTrace();
        }
    }
}

  The output is as follows:

The null pointer exception is caught here, and the prompt content: I heard that you are very busy, and I will throw an exception for you.
java.lang.NullPointerException: I heard that you are busy, throw an exception for you.
    at com.frank.chapter16.main.Test.main(Test.java:11)

  With the throw keyword, you can throw any type of exception. Of course, if you want, you can also throw Error. As for what Error is, the relationship with Exception will be explained in the next article. No need to delve into it for now.

  When throwing an exception, you can add the reason for throwing the exception, which makes it easier to locate the problem. Of course, it is generally not used like in chestnuts. This is just for simplicity.

  So far, the first half of the exception has been explained. In this article, it explains what is an exception, what is exception handling, and how to use the exception handling mechanism. I believe that everyone has a preliminary understanding of this little goblin. In the next article, I will explain which members of the Exception family are, how to use custom exceptions, and the correct posture in actual use of exception handling. Welcome everyone to continue to pay attention, and plan to update more than two articles per week in the future. If there are any missing or bad explanations, you are welcome to point out in time and make progress together!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325970887&siteId=291194637