Fill the hole, sort out the Java common exceptions. The correct use of exception in actual coding is very important, but the meaning of the interview is relatively small, because it is difficult to through the understanding and application of abnormal examining out a few words or a few lines of code, but we are answering at least three points: the exception class inheritance, common exception class, common exception class usage scenarios, below will be around here at three o ‘clock.

The inheritance of exception classes

image.png

In Java, all exceptions inherit from the Throwable class, a fully available class. The Exception category is further divided into UncheckedException (inherited from RuntimeException) and CheckedException (inherited from Exception, Does not inherit from RuntimeException.

To help understand, I have given two common subclasses under each category, such as Error including OutOfMemoryError, AssertionError, etc. UncheckedException includes NullPointerException and IllegalArgumentException. CheckedException includes IOException and InterruptedException. When drawing the inheritance relationship of exception classes, it is required to be able to clearly explain several categories and categorize several commonly used exception classes.

Common exception classes

The following category extends the commonly used exception class, lexicographical sort:

category Common exception classes
Error AssertionError,OutOfMemoryError, StackOverflowError
UncheckedException AlreadyBoundException, ClassCastException, ConcurrentModificationException,IllegalArgumentException, an IllegalStateException, IndexOutOfBoundsException, JSONException,NullPointerExceptionSecurityException, UnsupportedOperationException
CheckedException ClassNotFoundException, CloneNotSupportedException, FileAlreadyExistsException, FileNotFoundException,InterruptedException,IOException, SQLException, TimeoutException, UnknownHostException

The important thing to understand is the UncheckedException.

All of the above exception classes are very common, but some of them are poorly designed and should be noted:

  • ConcurrentModificationException: “fast” failure mechanism, but in fact, “fast” failure mechanism itself still cannot assure concurrent environment security, the reference source | from source code analysis not thread-safe collections of unsafe iterators. So, while this exception is common, don’t rely on it.
  • JSONException: This is common when json string parsing fails, but hides a lot of details of the failure and is often difficult to handle based on the exception. If you use JSON heavily in your project, you are advised to use a third-party JSON parsing library, such as Gson.
  • UnsupportedOperationException: this is a kind of coding on malignant compromise, often by the user in the members of the abstract class methods active throw, said the method also unrealized, etc., but because be UncheckedException, runtime to found that completely useless in safety during encoding. Try not to use it when coding yourself.
  • SQLException: Similar in cause to JSONException, but masking a wider range of failure details. SQLException is also a CheckedException, which makes the code bloated without solving the problem. Proposals. If you’re doing Java Web development, the popular ORM libraries can solve all of these problems.

Usage scenarios of common exception classes

There are still a few common exceptions, so here are the scenarios for each of the three categories and an example from each category.

Error

Error usually describes system-level errors that the programmer cannot actively handle — of course, system-level errors can also be caused indirectly by code, which is beyond the scope of our discussion. When a system-level Error occurs, the system environment is already unhealthy. Therefore, Error is not mandatory to capture or declare, that is, not to force processing. In most cases, only the exception information needs to be recorded (it is better if you can remember the system snapshot at the time).

OutOfMemoryError

An OutOfMemoryError is thrown by the JVM when there is insufficient memory available. It is generally caused by three reasons:

  • The heap Settings are too small to meet normal memory requirements
  • There is a memory leak in the code that takes up too much memory to be reclaimed
  • The GC algorithm chosen does not match some extreme application scenarios where there is too much memory fragmentation and not enough contiguous space to allocate to objects

The JVM will attempt a Full GC before throwing an OutOfMemoryError, and will only throw an OutOfMemoryError if there is still insufficient memory available after GC. Therefore, the programmer will not be able to deal with the problem actively and will have to wait until the program crashes to determine the cause.

The techniques for verifying outofMemoryErrors are enough to cover a single article.

UncheckedException

Strictly speaking, Error can also be classified as UncheckedException, but UncheckedException is more commonly used to describe an application-related Error that occurs at runtime, usually directly due to a code problem, and that the programmer is unable to actively handle. Note that system-level errors should be described by Error. Most cases of UncheckedException occur when code is broken, so UncheckedException does not enforce a catch or declaration, that is, it does not enforce processing. Generally, just log it.

The difference is that if possible, make sure UncheckedException is manageable (check and actively throw the exception before it is thrown passively).

JSONException is uncontrollable.

NullPointerException

NullPointerException is the most common UncheckedException. If a method or variable is referenced on a null pointer, the runtime throws a NullPointerException. Null pointer make program uncontrolled: if let the null pointer in program running period to transfer, use, we will not be able to determine the behavior of the program, also not sure catch NullPointerException program of the state.

The solution to this problem is simple:

  • Check early and actively throw exceptions
  • Separate and advance processing of boundary conditions
  • Try not to use NULL to indicate state, especially in collections

The first two principles apply to most UncheckedException; see String#toLowerCase() for an example. The third principle requires a trade-off between robustness and brevity, prioritizing simplicity over robustness.

CheckedException

Monkeys have a poor understanding of CheckedException. If you have a better understanding, I hope we can communicate. Here is the monkey “not in place” understanding.

CheckedException describes a less serious error caused by an external environment that should be handled proactively by the programmer. Note the distinction from system-level errors, which are usually unrecoverable. Therefore, CheckedException enforces a catch or declaration that the program ape must handle. Logging, wrapping and throwing again, and declaring in method signatures are the three most common practices.

Like UncheckedException, CheckedException is guaranteed to be manageable. The CheckedException is more controllable, not only checking proactively, but also taking appropriate action when an exception is caught.

However, the monkeys thought the existence of a large number of CheckedException was a mistake. FileAlreadyExistsException, for example, should be more active examination revealed by the user, and should not depend on the exception. For the exception that can be handled, it is essentially equivalent to the control flow problem, and the expression of the exception makes the control flow fuzzy. Sometimes, however, monkeys writing small projects declare exceptions directly in the method signature, all the way to main, in order to simplify the code. Well, everything is a trade-off.

IOException

IOException can occur for many reasons, but most of the time we don’t care about the details of the cause, because the file system is a less controllable factor, so we can deal with IOException as a granularity. Exceptions that require attention to detail should be handled case by case using a subclass of IOException.

Outlined FileAlreadyExistsException, FileNotFoundException, UnknownHostException, etc., are IOException subclasses. All three of these exceptions happen to be manageable.

InterruptedException is also important.

conclusion

In actual coding, we should properly use exceptions to express code design, and use the exception classes provided by the JDK whenever possible. There are a lot of exception classes built into the JDK, so we just need to learn a few commonly used exception classes and learn from them.


This article is published under the Creative Commons Attribution – Share alike 4.0 International License. All attribution and links to this article must be reserved.