Most of the suggestions for exceptions in the Java language believe that the checked exceptions should be prioritized in any case that the exceptions are certain to be captured. Language Design (the compiler forces you to list all checked exceptions that may be thrown in the method signature) and early works on style and usage support this advice. Recently, several famous authors have begun to think that non-checking exceptions play a more important role in excellent Java class design than previously thought. In this article, Brian Goetz examines the advantages and disadvantages of using non-checked exceptions.
?? Similar to C ++, Java also provides exception throws and capturing. However, unlike C ++, JAVA supports checked and non-checked exceptions. Java classes must declare any checked exceptions they throw in the method signature, and if any method is called, if it throws a checked exception of Type E, then it must capture E or declare it to throw E (or a parent class of E ). In this way, the language forces us to document all the expected methods that may exit a method.
?? For exceptions caused by programming errors, or exceptions that cannot be captured by the Program (removing the reference of a null pointer, array out-of-bounds, Division by zero, etc ), to prevent developers from handling these exceptions, some exceptions are named as non-check‑type exceptions (Exceptions inherited from runtimeexception) and do not need to be declared.
?? Traditional Viewpoint
?? In the following excerpt from Sun's "the Java tutorial, summarizes the traditional ideas about declaring an exception as a checked or non-checked type (for more information, see references ):
?? Because Java does not require methods to capture or Specify runtime exceptions, writing code that throws only runtime exceptions or makes all of their exception subclasses inherit from runtimeexception, it is attractive for programmers. These programming shortcuts allow programmers to write Java code without being disturbed by all picky errors from the compiler and without specifying or capturing any exceptions. Although this seems convenient for programmers, it bypasses Java capture or specifies the intent of the request, and may cause problems for programmers who use the class you provide.
?? A Checkpoint exception indicates useful information about the operation of a specified legal request. The caller may have no control over the operation and the caller needs to receive related notifications ?? For example, the file system is full, the remote connection has been closed, or the access permission does not allow this action.
?? If you only throw a runtimeexception because you do not want to specify an exception or create a subclass of runtimeexception, what do you get? You only get the ability to throw an exception without specifying it. In other words, this is a way to avoid exceptions thrown by documented methods. When is this beneficial? That is to say, when can it be helpful to avoid specifying a method? The answer is "almost never ."
?? In other words, Sun tells us that a checked exception should be a criterion. This tutorial continues to explain in multiple ways. An exception should be thrown instead of a runtimeexception ?? Unless you are a JVM.
?? In objective Java: programming language guide, Josh Bloch provides the following knowledge about checked and non-checked exceptions, these are the same as the suggestions in the "the Java tutorial" (but not exactly the same ):
?? Article 39th: exception is only applicable to abnormal conditions. That is to say, do not use exceptions for the control flow. For example, nosuchelementexception is captured when iterator. Next () is called rather than when iterator. hasnext () is checked for the first time.
?? Article 40th: checktype exceptions can be used for recoverable conditions, and runtime exceptions are used for programming errors. Here, Bloch responds to the traditional sun viewpoint ?? Runtime exceptions should only be used to indicate programming errors, such as violation of preconditions.
?? Article 41st: Avoid unnecessary inspection exceptions. In other words, do not use a check exception if the caller cannot recover from it, or the only foreseeable response will be program exit.
?? Article 3: throws an exception that matches the abstraction. In other words, the exception thrown by a method should be defined at an abstract level, which is consistent with what the method is, not necessarily with the underlying implementation details of the method. For example, a method for loading resources from a file, database, or JNDI should throw a resourcenotfound exception when the resource cannot be found (the exception chain is usually used to save the implicit cause ), instead of the underlying ioexception, sqlexception, or namingexception.
?? Review the orthodox view of non-checked exceptions
?? Recently, several distinguished experts, including Bruce Eckel and Rod Johnson, have publicly stated that although they initially fully agree with the orthodox view of checked exceptions, however, they have determined that the idea of exclusive use of checked exceptions is not as good as originally, and for many large projects, checked exceptions have become an important source of problems. Eckel proposed a more extreme view, suggesting that all exceptions should be non-check‑type; Johnson's view should be conservative, but it still implies that the traditional priority check-type exceptions are too much. (It is worth mentioning that the C # designer chooses to ignore checked exceptions in the language design so that all exceptions are non-checked, therefore, it is almost certain that they have rich Java technology experience. However, they did leave room for the implementation of checked exceptions .)
?? Some criticisms of checked exceptions
?? Both Eckel and Johnson have pointed out a list of similar issues about checked exceptions. Some are internal attributes of checked exceptions and some are attributes of specific implementations of checked exceptions in Java, there are also some simple observations, mainly about how the wide range of incorrect use of checked exceptions becomes a serious problem, which may cause this mechanism to be reconsidered.
?? Check type exception does not properly expose Implementation Details
?? How many times have you seen (or written) a method that throws sqlexception or ioexception, even if it looks unrelated to the database or file? For developers, summarize all exceptions that may be thrown in the initial implementation of a method and add them to the throws clause of the method (many ides even help you execute this task) is very common. One problem with this direct method is that it violates the 43rd ?? The abstraction level of thrown exceptions is inconsistent with that of the methods that throw them.
?? A method used to load the user summary should throw nosuchuserexception instead of sqlexception ?? The caller can predict that the user may not be able to find it, but does not know how to handle sqlexception. Exception chains can be used to throw a more appropriate exception without discarding details about underlying failures (such as stack tracking ), the abstraction layer is allowed to isolate the layers above them from the details of the layers under them, while retaining information that may be useful for debugging.
?? It is said that the JDBC package is designed in such a way that it is difficult to avoid this problem. Every method in the JDBC interface throws sqlexception. However, when accessing a database, different types of problems may occur, and different methods may be vulnerable to different error modes. A sqlexception may indicate a system-level problem (cannot connect to the database) and a logic problem (no more rows in the result set) or a specific data issue (the primary key of the row you just attempted to insert already exists or violates the entity integrity constraints ). Without an irrevocable attempt to analyze the message body, it is impossible for callers to distinguish these different types of sqlexception. (Sqlexception does support methods used to obtain database-specific error codes and SQL state variables. However, in practice, these methods are rarely used to differentiate different database error conditions .)
?? Unstable method Signature
?? The unstable method signature issue is related to the previous issue ?? If you only pass an exception through a method, you have to change the method signature and change all the code that calls the method each time you change the implementation of the method. Once the class has been deployed in the product, managing these fragile method signatures becomes an expensive task. However, this problem is essentially another symptom that does not follow the 43rd articles proposed by Bloch. When a method fails, an exception should be thrown, but the exception should reflect what the method does, rather than how it does it.
?? Sometimes, when programmers get bored with adding or deleting exceptions in method signatures due to implementation changes, they do not define the types of exceptions that may be thrown at a specific level by using an abstraction, instead, they declare all their methods as throwing an exception. In other words, they have determined that exceptions only cause troubles and basically shut them down. Needless to say, this method is generally not a good error handling policy for the vast majority of code that can be used at will.
?? Obscure code
?? Because many methods throw a certain number of different exceptions, the ratio of error handling code to the actual functional code may be high, making it difficult to find the code that actually completes the function in a method. Exceptions are reduced by centralized error handling, but one has three lines of code and six catch blocks (each of which only records exceptions or wraps and throws exceptions again) the method seems to be relatively inflated and will blur the original simple code.
?? Exception flood
?? We have seen such code, and an exception is caught, but there is no code in the Catch Block. Although this programming practice is obviously not good, it is easy to see how it happened ?? During prototype, someone wraps the Code through the try... Catch Block, and then forgets to return and fill in the Catch Block. Although this error is common, it is also a better tool to help us ?? The editor, compiler, or static check tool can easily detect and issue warnings when exceptions are drowned.
?? The extremely common try... Catch Block is another form of exception flooding and is more difficult to detect because it is caused by the abnormal class hierarchy in the Java class library (suspicious ). Let's assume that a method throws four different types of exceptions, and the caller will capture and record any of these exceptions and return them. One way to implement this policy is to use a try... Catch Block with four catch clauses, with one exception type. To avoid issues that are hard to understand, some developers will refactor the code, as shown in Listing 1:
Listing 1. Accidentally overwriting runtimeexception
Try {
Dosomething ();
}
Catch (exception e ){
Log (E );
}
?? Although the Code is more compact than the four catch blocks, it has a problem ?? It also captures any runtimeexception that may be thrown by dosomething and prevents them from spreading.
?? Excessive abnormal Packaging
?? If exceptions are generated in an underlying facility and spread up through many code layers, they may be captured, encapsulated, and re-thrown several times before being finally processed. When an exception is eventually recorded, the stack trace may have many pages, because the stack trace may be copied multiple times, each of which has one packaging layer. (In JDK 1.4 and later versions, the implementation of the exception chain has mitigated this problem to some extent .)
?? Replacement Method
?? Bruce Eckel, author of thinking in Java (see references), claims that after years of using the Java language, he has come to the conclusion that a checked-type exception is an error ?? A test that should be declared as a failure. Eckel advocates that all exceptions be considered non-checkable and provides classes in Listing 2 as a way to convert a checkable exception to a non-checkable exception, at the same time, retain the ability to capture specific types of exceptions when exceptions spread up from the stack (for an explanation of how to use this method, see his article in the references section ):
Listing 2. Eckel exception adapter class
Class exceptionadapter extends runtimeexception {
Private final string stacktrace;
Public exception originalexception;
Public exceptionadapter (exception e ){
Super (E. tostring ());
Originalexception = E;
Stringwriter Sw = new stringwriter ();
E. printstacktrace (New printwriter (SW ));
Stacktrace = Sw. tostring ();
}
Public void printstacktrace (){
Printstacktrace (system. Err );
}
Public void printstacktrace (Java. Io. printstream s ){
Synchronized (s ){
S. Print (getclass (). getname () + ":");
S. Print (stacktrace );
}
}
Public void printstacktrace (Java. Io. printwriter s ){
Synchronized (s ){
S. Print (getclass (). getname () + ":");
S. Print (stacktrace );
}
}
Public void rethrow () {Throw originalexception ;}
}
?? If you look at the discussion on the Eckel web site, you will find that the responder is severely split. Some people think that his proposal is absurd; others think that this is an important idea. (In my opinion, although it is really difficult to properly use exceptions, and there are a large number of examples of poor use of exceptions, but most people who agree with him do this for the wrong reason, this is similar to the situation in which a politician runs on a platform where he can obtain chocolate at will and will receive a large number of votes from ten-year-olds .)
?? Rod Johnson is the author of J2EE design and development (see references). This is one of the best books I have read about Java Development and J2EE. He took a less radical approach. It lists multiple categories of exceptions and determines a policy for each category. Some exceptions are essentially secondary return code (which usually indicates violation of business rules), while some exceptions are variants of "some type of terrible error" (such as database connection failure. Johnson advocates the use of checktype exceptions for the first type of exceptions (optional return code), while the use of runtime exceptions for the latter. In the "something terrible wrong" category, the motivation is to simply realize that no caller can effectively handle this exception, as a result, it may spread up the stack in various ways and minimize the impact on intermediate code (and minimize the possibility of exception flooding ).
?? Johnson also listed an intermediate situation and asked him a question: "Is it just a few callers who want to handle the problem ?" In these cases, we recommend that you use non-checkable exceptions. As an example of this class, he lists JDO exceptions ?? In most cases, JDO exceptions indicate that the caller does not want to handle them. However, in some cases, it is useful to capture and process exceptions of specific types. It is recommended that non-checktype exceptions be used here, instead of making other JDO classes compensate for this possibility by capturing and re-throwing these exceptions.
?? Non-checked exception
?? The decision on whether to use a non-checkable exception is complex and apparently there is no clear answer. Sun's advice is to use them in any situation, and the C # method (that is, what Eckel and others agree with) does not use them in any situation. "There is still an intermediate situation," others said ."
?? By using exceptions in C ++, all exceptions are non-checkable, I have found that one of the biggest risks of non-checkable exceptions is that they are not documented in the way they are used. Unless the API creator explicitly files the exceptions to be thrown, the caller cannot know what exceptions will be caught in their code. Unfortunately, my experience is that most C ++ APIs are very poorly documented, in addition, even well-documented APIs lack sufficient information about exceptions that may be thrown from a given method. I don't see any reason to say that this problem is not the same common for Java class libraries, because the Jav class library is heavily dependent on non-checked exceptions. It is very difficult to rely on your own or your partner's programming skills; if you have to rely on someone's documented skills, for his code, you may have to use 16 frames in the call stack as your main error handling mechanism, which is panic.
?? The document-based problem further emphasizes why laziness is a bad reason for choosing to use non-checked exceptions, because it adds a burden to the package for docization, non-checkable exceptions should be more advanced than checking exceptions (when documented, the non-checkable exceptions you throw become more important than checking exceptions ).
?? Documented, documented, and documented
?? If you decide to use a non-checkable exception, you need to thoroughly document this option, including all non-checkable exceptions that may be thrown by documenting a method in javadoc. Johnson recommends selecting checktype and non-checktype exceptions based on each package. When using non-checkable exceptions, remember that even if you do not capture any exceptions, you may need to use try... finally blocks to clear the database, for example, closing the database connection. For checked exceptions, try... catch is used to indicate the addition of a finally clause. We do not have this support for non-checked exceptions.