Java basic grammar (10)-Recognizing exceptions

Article Directory


Java basic grammar (10)-Recognizing exceptions


Continuing from the previous blog Java basic grammar (9)-String class


Outline of this content introduction


Insert picture description here



One, first met the anomaly


Students often ask when they see an anomaly, what is the anomaly? In our previous studies, we have actually been exposed to exceptions in Java.


1. Arithmetic abnormality


First of all, the first exception we encountered was the arithmetic exception we encountered when talking about the division operator.


See the following code

Insert picture description here


We have 0 in the position of the molecule to run the above code.

operation result:

Insert picture description here

2. Array subscript out of bounds exception


In the array article, we also mentioned the problem of array out-of-bounds


Let's look at the following code:


Insert picture description here



Run-time results:


Insert picture description here



View abnormal information

Insert picture description here



3. Null pointer exception


Null pointer exceptions often appeared in previous studies


Look at the following code


Insert picture description here


We set the array array to null, and then to access the array, a null pointer exception occurred.


operation result:

Insert picture description here


These abnormalities need to be accumulated by us in peacetime,

The so-called exception refers to a mechanism for notifying the caller when an error occurs in the program at runtime.


Keyword "runtime"
Some errors are like this. For example, System.out.println is misspelled and written as system.out.println. At this point, an error occurs during the compilation process, which is a "compilation period" error.
The runtime refers to the error that occurs during the execution of the program by the JVM after the program has been compiled and passed the class file.


4. Exception handling


There are many types of exceptions, different types of exceptions have different meanings, and there are different ways to handle them. (Just understand here)


Defensive programming


Errors exist objectively in the code. Therefore, we have to notify the programmer in time when there is a problem with the program. We have two main ways


LBYL: Look Before You Leap.
Do a sufficient check before the operation.
EAFP: It's Easier to Ask Forgiveness than Permission.
"It is easier to obtain forgiveness after the fact than to obtain permission beforehand". That is to operate first, and then deal with problems.


In fact, it is very easy to understand. It is a very vivid metaphor to understand:


For example, if there is a girl you like very much, and you want to pull her hand, how many ways are there?
The first way LBYL: ask: can I hold your hand?


This is to double check before operation.


The second way EAFP: Pull your hand directly first. If she shakes it away, she will talk about other things. If she doesn't refuse, she will pull it.


This is "it is easier to obtain forgiveness after the fact than to obtain permission beforehand".


Just understand, no need to remember.


5. Abnormal benefits


Let's take a look, what exactly are the above two styles when dealing with code?

Let’s first give a specific scene to deal with the abnormal code at the beginning of the game of Honor of Kings


LBYL style code (no exceptions are used)
Insert picture description here


After each step of the code is executed, it must be checked and confirmed to be correct before proceeding to the next step. This is to check before the operation.


EAFP style code
Insert picture description here


Here we can experience Java style code exception handling

Insert picture description here


Comparing two different styles of code, we can find that using the first method, the normal process and error handling process code are mixed together, and the code as a whole is more confusing. The second method is separate from the normal process and the error process. It is easier to understand the code.


Second, the basic grammar of the exception


Next, we officially began to explain the basic syntax of handling exceptions in Java.


1. Basic format


Basic format for handling exceptions in Java


Insert picture description here


2. Whether to deal with the impact of exceptions on the program


Let's look at a set of codes:


Insert picture description here


In this group of codes, in the second step of code execution, we have an array out-of-bounds exception, so will the "hello" in the third step be printed?


We run the program and see the result

Insert picture description here


"Hello" is not printed, so why is this? At this time, the program is abnormal, and when the program is abnormal, the code will not be executed.


So we still want to execute this "hello", so what should we do?


We will write the code in the following format:

Insert picture description here


operation result;

Insert picture description here



hello was also successfully printed. That is to say, in this way, the code throws an exception, and after the exception is caught, the code will continue to execute backwards.


Then some students said that the e we defined is not used, let’s look at the use of e


Insert picture description here


e.printStackTrace — Print the trace of the stack where the exception occurred

Let's look at the results of the program at this time

Insert picture description here


At this time, the location of the stack where the exception occurred is printed out. This is a function of e.


Then some students came to ask, why can't the previous "hello" be printed out, but after the try...catch catches the exception, it can be printed out?


Insert picture description here

3. Use try… catch problems that need attention


1. In the catch block, the corresponding exception must be caught. If the exception thrown by the program is in the catch block and cannot be caught, it will be handed over to the JVM for processing.


Look at the following code:

Insert picture description here


The array out-of-bounds exception was not caught in the catch block. Let's take a look at the results of the operation.

Insert picture description here



Hand over to the JVM for processing, the program terminates, and no longer executes downwards.


2. Multiple exceptions can be caught by catch


We can catch the exception with multiple catches after the try, as in the following code:

Insert picture description here

The results of running the program are as follows:

Insert picture description here


We know that all exceptions inherit from Exception, so someone asked, can we directly catch an Exception?


Let's try it,


We know that the order of catching exceptions is executed in the order in which the code is written, let’s take a look at this code

Insert picture description here


When the parent exception of Exception is placed at the beginning, the following catch exception will be reported as an error.


If you write like this, then all the exceptions after Exception are invalid. Why? Because no matter what exception is in try {}, it will be caught in the Exception step, and the subsequent catch exceptions will naturally fail.
So when we wrote Exception in the front to catch the exception, don't catch other exceptions later.


Then some classmates said that we want to save trouble, then we will catch Exception in the future.


Of course not. In this case, we cannot distinguish what anomaly we caught. Therefore, it is not recommended that you directly catch an Exception.
3. It is not recommended to catch an Exception directly


Some students want to save trouble and want to merge two exceptions into one for capture, we only need to connect the two exceptions with |.


Give an example:

Insert picture description here


Take a look at the results:

Insert picture description here

Run successfully.


Summary :


1. In the catch block, the corresponding exception must be caught. If the exception thrown by the program is in the catch block and cannot be caught, it will be handed over to the JVM for processing.
2. Multiple exceptions can be caught by catch
3. It is not recommended to catch an Exception directly
4. You can use | to handle two exceptions at the same time, as in the above example.


4. Regarding the handling of exceptions


There are many types of exceptions, and we have to decide according to different business scenarios.


For more serious problems (such as scenarios related to counting money), the program should be directly crashed to prevent more serious consequences
For less serious problems (most scenarios), you can record the error log, and notify the programmer in time through the monitoring alarm program
For problems that may be recovered (network-related scenarios), you can try to retry.
In our current code, the simplified second method is adopted. The error log we record is the abnormal method call information, which can quickly let us find the abnormal position. In the actual work, we will adopt A more complete way to record abnormal information.


About the "call stack"


There is a mutual calling relationship between methods. This calling relationship can be described by "call stack". In the JVM, there is a memory space called "virtual machine stack" that specifically stores the calling relationship between methods. When in the code When an exception occurs, we can use e.printStackTrace(); to view the call stack of the abnormal code.


5.Finally use


Let's look at the learning of abnormal basic grammar again

Insert picture description here


We can follow finally after we see try...catch

Let's talk about the characteristics of finally


Regardless of whether this code throws an exception, the contents of finally will be executed. So finally often comes to do some aftermath. For example: close resources


Let’s take a look at this set of codes

Insert picture description here

Let me test everyone, what is the result of this set of code execution?

The results of the operation are as follows:

Insert picture description here

The printed result is 2. Why is this?

First of all, we need to be clear that the content of finally will be executed.


Let's analyze:

In the try block, an exception occurs when printing array[4], and the following return statement is no longer executed, so finally the finally block is executed, returning 2.


Let's look at another code example:

Insert picture description here

What is the result of this set of code execution?


operation result:

Insert picture description here


Finally returned 2.


This is again clear:


The content of finally will be executed


finally use summary :


1. The code in the finally block will eventually be executed
2. It is not recommended to have a return statement in finally.


6. Exception handling process


Insert picture description here


Okay, so far, we can say clearly about the try...catch...finally and exception handling process and other issues, so you must remember to use try...catch in the process of writing code in the future, not just hand it over to the JVM Deal with it, well, let's start the next piece of content-throw an exception.


7. Throw an exception


In addition to the Java built-in classes that will throw some exceptions, the programmer can also manually throw some exceptions. Use the throw keyword to complete this operation.


throw generally throws an exception you want to throw (or a custom exception)


(1) The use of throw


Let's look at the code example:

Insert picture description here


We used throw new to make an arithmetic exception. Why do we need new? Because the arithmetic exception itself is also a class, it must be instantiated.


Let's look at the runtime results;


Insert picture description here


An exception was successfully thrown, but there is a downside to writing this way. We threw an exception. However, we just threw this exception but did not handle it, so in the end the program was handed over to the JVM for processing after an exception, and the program finally terminated.


(2) Declare an exception


For those of us who call the devide method, if there is a lot of content in the devide method, we can't see that devide will throw an exception. So in order to let people who call the devide method know, we call this method will throw this exception, under normal circumstances, we will declare an exception for this method. So how to declare it?


Declare that this method will throw an exception through throws


Let's look at the code example below:

Insert picture description here

The method caller knows that calling the method may throw an arithmetic exception, and uses try...catch to catch the exception.


operation result:

Insert picture description here

(3) Summary

Insert picture description here

Three, Java exception system


So how many kinds of abnormalities are there? To understand this problem, we need to know Java's exception system.


Insert picture description here


The above figure does not list all the exceptions, just a rough demonstration.


In Java, the exceptions we see actually correspond to a class.


From the figure above, we can see that the entire Java exception system is inherited from the top-level class Throwable, so Throwable is the parent class of all exceptions and errors.


For Throwable, there are two subclasses that directly inherit this class,


Error and Exception.


Let's take a look at the explanation of Throwable in the jdk_api help manual

Insert picture description here


We are talking about exceptions in this article. Why does an error occur again?

Let's also recognize the following Error

For example, let's write a code:


Insert picture description here


The following results appeared after running:

Insert picture description here


Let's compare:

Insert picture description here


Exceptions end with Exception, and errors end with Error.

For Error-this kind of error must be solved by the programmer himself.

As for Exception, the program can resolve the exception.

The exception is divided into the following

Insert picture description here


Runtime Exception is the arithmetic exception, array out-of-bounds exception, type conversion exception and so on that we mentioned above, so some students have asked?

What is a runtime exception?
Runtime exceptions are exceptions thrown when the program is running
What is a compile-time exception?
Compile-time exceptions are exceptions thrown when the program is compiled


If a piece of code may throw a checked exception, it must be handled explicitly.


There are two ways of explicit processing:


a) Wrap it with try catch
b) Add an exception description to the method, which is equivalent to handing over the processing action to the superior caller
Don't forget IDEA's magical alt + enter, which can quickly correct the code.

Summary :

Insert picture description here


Four, custom exception class


Although there are a wealth of exception classes built in Java, there may be some situations in our actual scenarios that require us to extend the exception classes and create exceptions that meet our actual conditions.


Let's implement a simple custom exception class


First of all, we have to customize an exception class while inheriting a parent class exception

Insert picture description here


So how do we use this custom exception?

Let's take a look

Insert picture description here


operation result:

Insert picture description here



This is the use of our custom exception.

Let's have another code example

Below we give a real business scenario


For example, we implement a user login function.


Insert picture description here


At this time, we may need to throw two exceptions when dealing with user name and password errors. We can extend (inherit) the existing exception class and create an exception class related to our business.


Insert picture description here


At this point, our login code can be changed to


Insert picture description here


Note for custom classes :


1. Custom exceptions usually inherit from Exception or RuntimeException
2. The exception inherited from Exception is the checked exception by default
3. The exceptions inherited from RuntimeException are unchecked exceptions by default.



Well, today’s knowledge is shared here. I hope you will practice more and master it. Thank you for your appreciation and attention! !




Thank you for your appreciation!




Finish!