Pits, sort out common exceptions for Java. Correct use of exceptions in the actual coding is very important, but the significance of the interview is relatively small, because the understanding and application of the anomaly is difficult to be examined by a few words or a few lines of code, but we answer at least three points: the exception class inheritance, common exception classes, common exception class usage scenarios, the following will be around these three points.
Inheritance relationships for exception classes
In Java, all exceptions are inherited from the Throwable class (a fully available class). The whole is divided into error, exception two large categories, exception large categories are divided into uncheckedexception (inherited from RuntimeException) and Checkedexception (inherited from Exception, But not inherited from RuntimeException).
To help understand, I gave two common subcategories under each category, such as error including OutOfMemoryError, Assertionerror, etc. uncheckedexception including NullPointerException, Illegalargumentexception;checkedexception includes IOException, interruptedexception. When interviewing for the inheritance of abnormal classes, it is required to clearly describe several categories and classify the common exception classes.
Common exception classes
The following sub-categories expand the common exception class, dictionary ordering:
| category |
Common Exception Classes |
| Error |
Assertionerror, OutOfMemoryError, Stackoverflowerror |
| Uncheckedexception |
Alreadyboundexception, ClassCastException, Concurrentmodificationexception, IllegalArgumentException, IllegalStateException, Indexoutofboundsexception, Jsonexception, NullPointerException, SecurityException, Unsupportedoperationexception |
| Checkedexception |
ClassNotFoundException, Clonenotsupportedexception, Filealreadyexistsexception, FileNotFoundException, Interruptedexception, IOException, SQLException, TimeoutException, unknownhostexception |
What needs to be emphasized is the uncheckedexception.
The above exception classes are very common, but a few of the exception class design is not good, you need to note:
- Concurrentmodificationexception: Implementation of the "rapid failure" mechanism, but in fact, the "fast failure" mechanism itself still cannot guarantee the security in the concurrency environment, reference source | The unsafe iterator that parses the non-thread-safe collection class from the source code. Therefore, although this exception is common, do not rely on it.
- Jsonexception: Common in cases where JSON string parsing fails, but a large number of failure details are obscured, and it is often difficult to deal with that exception. If JSON is used extensively in your project, we recommend using a third-party JSON parsing library, such as Gson.
- Unsupportedoperationexception: This is a kind of code on the vicious compromise, often in the member method of the abstract class is actively thrown by the user, indicating that the method has not been implemented, etc., but because it is uncheckedexception, the runtime can be found, is completely unhelpful to security during encoding. Try not to use it when coding yourself.
- SQLException: Similar to the jsonexception cause, but with a wider range of failure details. At the same time, SqlException is still a checkedexception, in the case can not solve the problem, but also make the code bloated. Suggested the same. If you do Java Web Development, the popular ORM libraries can solve these problems.
Usage scenarios for common exception classes
Common exceptions or a bit more, the following are explained in the above three categories of usage scenarios, and in each category selected an example to explain.
Error
Error usually describes system-level errors, and the program ape cannot take the initiative-and of course, system-level errors may be indirectly caused by the code, which is beyond our scope of discussion. System-level errors occur when the system environment is unhealthy, therefore, error does not force capture or declaration, that is, do not force processing, generally only need to record the exception information (if you can write down the system snapshot is better).
OutOfMemoryError
When the available memory is low, OutOfMemoryError is thrown by the JVM. It is generally caused by three reasons:
- The heap settings are too small to meet the normal memory requirements
- There is a memory leak in the code that consumes a lot of memory and cannot be recycled
- The selected GC algorithm does not match some extreme scenarios, too much memory fragmentation, and no large enough contiguous space allocated to the object
Before the JVM throws a outofmemoryerror, it attempts to make a full GC and throws OutOfMemoryError if the available memory is insufficient after the GC. Therefore, the program ape must not take the initiative to deal with this problem, can only wait until the program crashes and then check the cause.
The skill of verifying outofmemoryerror is enough to open an article alone, this article does not make in-depth.
Uncheckedexception
Strictly speaking, error can also be classified as uncheckedexception, but we are more accustomed to using uncheckedexception to describe the run-time occurrence, usually due to code problems directly caused by the program-related errors, and the program ape can not be actively processed. Note that system-level errors should be described by error. Uncheckedexception Most of the situation occurs when the code is written down, so uncheckedexception is not forced to capture or declare, that is, do not force processing, generally write down the log.
The difference is that, if possible, ensure that the uncheckedexception is controllable (check before the exception is thrown and actively throw it).
The jsonexception is not controllable.
NullPointerException
NullPointerException is the most common uncheckedexception. If you refer to a method or variable on a null pointer, the runtime throws NullPointerException. The null pointer makes the program not controllable: If the null pointer is arbitrarily passed and used during the program's run time, we will not be able to determine the behavior of the program, nor can we determine the state of the program at the time the NullPointerException was captured.
The way to solve this problem is simple:
- Check early and proactively throw exceptions
- Separate, advance processing of boundary conditions
- Try not to use NULL to represent the state, especially in the collection
The first two principles are common to most uncheckedexception, and can refer to the example of String#tolowercase (). The third principle requires a tradeoff between the robustness and brevity of the code, the limited assurance of brevity, the need for robustness and robustness.
Checkedexception
Monkey's understanding of the checkedexception is not in place, if you have a better understanding of the hope to exchange a bit. The following talk about monkeys "not in place" understanding.
Checkedexception describes the less serious errors caused by the external environment, and the program ape should take the initiative to deal with it. Note System-level errors are usually not recoverable as system-level errors are distinguished. Therefore, the Checkedexception force captures or declares that the program ape must deal with. It is the three most common practice to log logs, which are then thrown again after packaging and declared in the method signature.
As with Uncheckedexception, Checkedexception is also guaranteed to be controllable. The controllability of the checkedexception is more demanding, not only to take the initiative to check, but also to make appropriate treatment when the anomaly is caught.
However, monkeys believe that the existence of a large number of checkedexception is a mistake. such as Filealreadyexistsexception, should be the user actively check the discovery, and should not rely on the exception. For the exception that can be handled, it is essentially equivalent to the control flow problem, and the abnormal expression instead makes the control rheological blur. But sometimes monkeys write small projects, and in order to simplify the code, directly declare the relevant exception in the method signature, and all the way to declare the main method. Well, everything is a trade-off.
IOException
There are a lot of reasons for IOException, but many times we don't care about the details, because the filesystem is a less controllable factor, and we can use IOException as the granularity, and some exceptions that need to be concerned with the details, the subclass of IOException should be used. dealt with in a sub-situation.
The Filealreadyexistsexception, FileNotFoundException, unknownhostexception, etc. summarized above are the subclasses of IOException. These three kinds of anomalies happen to be handled.
Digging a pit, interruptedexception is also very important, after the special write an article to organize.
Summarize
In the actual coding work, we should correctly use the exception expression code design, and use the exception class provided by the JDK whenever possible. There are a lot of exception classes built into the JDK, and we just need to master some common exception classes and then extrapolate.
Java Learning Exchange QQ Group: 589809992 prohibit small talk, non-happy do not enter!
Java Common Exception collation