Similar to C , Java language also provides abnormal throwing and capture. However, with C is that Java language supports inspection and non-checking exceptions. The Java class must declare any of the inspected exceptions thrown in the method signature, and for any method, if it calls the method throws a type E, it must be captured or declared as a throw E (or a parent class). In this way, the language enforces our documentation control may exit all expected ways of a method. For exceptions caused by programming errors, or not to expect an exception captured by the program (release a null pointer, array, division, etc.), in order to prevent the developer from handling these abnormalities, some abnormalities are named Check an exception (ie those who inherit from RuntimeException) and do not need to be declared. The traditional view is in the exception from Sun's "The Java Tutorial", summarizes traditional views about the abnormal statement as an inspection or non-check type (more information, please refer to the reference): Because of the Java language No way to capture or specify the runtime exception, so write only the runtime exceptions or make their abnormal subclasses inheritance from RuntimeException, which is attractive for programmers. These programming shortcuts allow programmers to write Java code without being disturbed from all pick-up errors from the compiler, and do not have to specify or capture any exceptions. Although this seems to be more convenient for programmers, it avoids Java capture or designated intentions, and for programmers who use the class you can lead to problems. The inspection-type exception represents useful information about the operation of a legally specified request, the caller may have not controlled the operation, and the caller needs to be relevant notifications - for example, the file system is full, or the remote is closed, or the remote connection is closed. Or access to this action is not allowed. If you just throw a runtimeException, or create a subclass of RuntimeException, then have you changed? You just got an abnormality that throw an exception without having to specify this. In other words, this is a way to avoid an abnormality that the documentation method can be thrown. When is this beneficial? That is, when is it possible to avoid the behavior of a method? The answer is "almost never." In other words, SUN tells us that the inspection exception should be guidelines. The tutorials continue to explain in a variety of ways, usually should be thrown instead of runtimeexception - unless you are JVM. In Effective Java: Programming Language Guide (see Resources), Josh Bloch provides the following knowledge points about check-type and non-inspected exceptions, which are consistent with the recommendations in The Java Tutorial (but not Completely strictly consistent): Article 39: Only use exceptions for abnormal conditions. That is, do not use an exception for the control flow, for example, capture NosuchelementException when calling iterator.next () during the first check of item.hasNext (). Article 40: Use an inspection-type exception to recoverable conditions to use the running time of programming errors. Here, Bloch responds to traditional Sun views - running abnormalities should only be used to indicate programming errors, such as violating preamp.
Article 41: Avoid unnecessary use inspection types. In other words, the case where the caller cannot recover from it, or the only foreseeable response will be the program exit, do not use the check-type exception. Article 43: Throw an abnormality that is adapted to abstract. In other words, the exception thrown by a method should be defined at an abstraction level, which is consistent with the method, and does not necessarily consistent with the underlying implementation of the method. For example, a method from files, databases, or JNDI load resources should throw some resourceNotFound anomalies when they cannot find resources (usually using an exception chain to save implicit), not a more underlying IOException, SQLException, or Namingexception. Re-examining the orthodox point of non-inspection-type unusual, several respectable experts, including Bruce Eckel and Rod Johnson, have disclosed despite their initial intention of the orthodox point of examination of the inspection-type abnormal, but they have already identified exclusive use inspection-type abnormalities The idea did not appear as good, and for many large projects, inspections have become an important source of issues. Eckel proposes a more extreme view, it is recommended that all exceptions should be non-inspected; Johnson's point of view is conservative, but still implies that traditional priority selection is excessive. (It is worth mentioning that the C # designer chooses to ignore the inspection exception in language design, making all anomalies are non-inspected, so they can affirm their experience in Java technology. However, they did check it later. The realization of an abnormality leaves space.) Both of the criticism of check-type exceptions, Eckel and Johnson pointed out a list of similar problems of inspections; some are intrinsic properties of inspection-type abnormalities, some are inspected exceptions in Java The properties of the specific implementation in the language, there are some simple observations, mainly about how the extensive error of inspection-type abnormalities becomes a serious problem, resulting in that the mechanism may need to be re-considered. How many times you have seen (or written) a method of seeing (or writing) a method that throws SQLException or IOException, even if it doesn't matter if it doesn't matter if it doesn't matter? For developers, all exceptions that may be thrown in one way are summarized in the initial implementation of a method and increase them to the method's ThROWS clause (many IDEs even helping you to do this task) are very common. One problem with this direct method is that it violates the abnormality of paragraph 43 of Bloch - the abnormality lying on the abnormality is inconsistent with the method of throwing them. A method for loading a user profile, should throw NosuchuseRexception when not finding the user, not the SQLException - the caller can make it good to the user may not find, but do not know how to handle SQLException. The abnormal chain can be used to throw a more appropriate exception without discarding details about the underlying failure (such as stack tracking), allowing the abstraction layer to be separated from the layered detail below them. Come, while retaining information that may be useful for debugging. It is said that the design of the JDBC package takes a way that it is difficult to avoid this problem. Each method in the JDBC interface throws SQLException, but in the process of accessing a database, there may be a variety of different types of problems, and different methods may vulnerable to different error modes.
A SQLException may indicate a system-level issue (not connected to the database), the logic problem (there is no more rows in the result set) or a specific data problem (you just try to insert the primary key that exists or violates the entity integrity). If there is no unforgivable attempt to analyze the negligence of the text body, the caller is impossible to distinguish these different types of SQLException. (SQLException is indeed for obtaining a database specific error code and SQL status variables, but these are rarely used to distinguish different database error conditions.) Unstable method Signature unstable method signature problem is in front Question Related - If you just pass an exception through a method, you have to change its method signature when you change the method, and change all the code to call the method. Once the class has been deployed to the product, managing these fragile methods will become an expensive task. However, this problem is essentially another symptom of Article 43 of Bloch. Methods should throw an exception when encounter failure, but this exception should reflect what the method does, not what it does. Sometimes, when the programmer is bored from the method signature, when the change is bored from the method signature, they are not bored by using an abstraction to define the possible type of exception, but only all the methods are declared. To throw an Exception. In other words, they have already identified an exception only leads to trouble and basically shuts it off. Needless to say, this method is usually not a good error handling policy for most of the most useful code. It is difficult to understand because many methods throw a certain number of different abnormalities, and the error handling code may be as high as the actual functional code, so that it is difficult to find a code in a way to actually complete the function. An exception is a way to reduce the code by centralized error handling, but a method with three lines of code and six catch blocks (where each block is only recorded or packaged, and the exception is re-thrown) looks more expanded and makes it Simple code becomes blurred. Excessive flooding we have seen such code, where an exception is captured, but there is no code in the Catch block. Although this programming practice is obviously bad, it is easy to see how it happens - during prototyping, someone packs code through the Try ... Catch block, and then forgets to return and fill the Catch block. Although this mistake is very common, this is also better tools to help us with one of our places - for an abnormal place, can easily detect and issue a warning through editor, compiler, or static check tool. Extremely universal Try ... catch block is another form of abnormal submergence and more difficult to detect because this is caused by the structure of the anomalous class hierarchy in the Java class library (suspicious). Let us assume that one method throws four different types of exceptions, and the caller encounters any of these exceptions, records them, and returns. One way to achieve this strategy is to use a Try ... Catch block with four CATCH clauses, each of which is one. In order to avoid problems that the code is difficult to understand, some developers will reconstruct the code, such as Listing 1: Listing 1. Unexpectedly submerge RuntimeExcectionTry {DOSMETHING ();} Catch (Exception E) {log (e);} The code is more compact than four CATCH blocks, but it has a problem - it also captures any runtimeException that may be thrown by DOSMETHING and blocks them from spreading. Excessive abnormal packaging If an abnormality is generated in a bottom facility and diffuses through many code layers, it may be captured, packaged, and re-throw several times before eventually being processed.
When an exception is finally recorded, the stack tracking may have many pages, because the stack tracking may be copied multiple times, each of which is once. (In JDK 1.4 and later versions, the implementation of the abnormal chain relieves the problem to some extent.) Replacement method Bruce Eckel, Thinking In Java (see Resources) Author, claiming to use Java language for many years He has drawn such a conclusion that the examination is an error - a test that should be declared as a failure. ECKEL advocates all anomalies as a non-check-type, and provides a method in Listing 2 as a method that converts the inspection-type abnormality into a non-check-type exception, while retaining a particular type of abnormality when an exception is spreading upward from the stack. capacity (explanation on how to use this method, see his article in the Resources 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 rechet ()} public void Rethrow () {throw OriginalException If you look at the discussion on the Eckel's Web site, you will find that the response is severely split. Some people think that his proposal is ridiculous; some people think this is an important idea. (My point is that although it is really difficult to use it properly, and the exception is in a large number of exquisite examples, most of them agree with him because of the wrong reason, this is in relation to a politician One of the places where you can get a chocolate will have a large number of puzzle tickets for a ten-year-old child.) Rod Johnson is the author of J2EE DESIGN AND DEVELOPMENT (see Resources), this is what I read. One of the best books in Java development, J2EE and other aspects. He takes a less radical approach. He lists multiple categories of abnormalities and determines a policy for each category. Some abnormalities are essentially a secondary return code (which usually indicates violations of business rules), and some abnormal variants "have a terrible error" (such as database connection failure). Johnson advocates the use of check-type exceptions for the first category of exceptions (optional return code), and the latter uses running time.