[Reading notes] "effective Java" 9th Chapter exception

Source: Internet
Author: User
Tags throwable

57th: Use exceptions only for exception cases
    • Exception mechanisms are used in unusual situations, and few JVM implementations attempt to optimize them. In modern JVM implementations, exception-based patterns are much slower than standard patterns.
    • Putting the code in the Try-catch block instead prevents the modern JVM from implementing some specific optimizations that might otherwise have been implemented.
    • A well-designed API should not force its clients to use exceptions for normal flow of control. If a class has a "state-related" method, that is, a method that can be called only under certain unpredictable conditions, the class should also have a separate "state test" method, which indicates whether the state-related method can be called. For example, the iterator interface has a "state-dependent" next method, and the corresponding state test method Hasnext. Alternatively, if the object is in an inappropriate state, calling a "state-dependent" method returns a recognizable value, such as null.
    • Choose the principle of both the state test method and the recognizable return value. If the visitor does not synchronize and the object is accessed concurrently, select "recognizable return value" because there is a time interval between the methods that call the state test method and the state-related method. If other aspects are equal, select the "state test method", because there is better readability, and for improper use, the "state-related" method throws an exception to facilitate detection and correction of errors.
58th: Use the exception for recoverable cases, use run-time exceptions for programming errors
    • The Java programming language provides three types of thrown structures: inspected exceptions, run-time exceptions, and errors. Run-time exceptions and errors belong to an unchecked exception.
    • Use the principle of a inspected exception or a non-inspected exception:
    1. If you expect the caller to be able to recover appropriately, use the exception that is being inspected.
    2. Use a run-time exception to indicate a programming error.
    • Any non-inspected throw structure you implement should be a subclass of runtimeexception (direct or indirect). Because errors are reserved by the JVM to indicate insufficient resources, constraint failures, or other conditions that make the program unable to continue execution.
    • You can define a throw structure that is not a subclass of exception, RuntimeException, or error. In a behavioral sense they are equivalent to a normal examined exception (that is, a subclass of exception, not a subclass of RuntimeException). But do not define such a class, nothing good, will only bother the user.
59th: Avoid unnecessary use of the exception being inspected
    • If a method throws one or more inspected exceptions, the code that invokes the method must handle the exception in one or more catch blocks, or it must declare that it throws an exception and let them propagate. Either way, the programmer adds a burden that cannot be ignored.
    • If using the API correctly does not prevent this exception condition from being generated, and once an exception is generated, the programmer using the API can take a useful action immediately, using the exception that is being examined, otherwise it is more appropriate to use an unchecked exception.
    • A method of turning a check exception into an unchecked exception, dividing the method that throws the exception into two methods, where the first method returns a Boolean indicating whether an exception should be thrown. This method is the same as the "state test Method" in 57th, and the problem of the "state test Method" (concurrent access) also exists here.
60th: Preferential use of standard exceptions
    • Benefits of reusing existing exceptions:
    1. Make your API easier to learn and use.
    2. The program is very readable because there are no exceptions that many programmers are unfamiliar with.
    3. The fewer exception classes mean that the smaller the footprint, the less time it takes to load these classes.
    • Common reusable exceptions

Exception Type Use occasions
IllegalArgumentException Incorrect parameter value for non-null
Illegalstateexcepition For method calls, the object state is not suitable for
NullPointerException Use NULL if NULL is forbidden
Indexoutofboundsexception Subscript parameter value out of bounds
Concurrentmodificationexception Concurrent modifications are detected in the case of a non-concurrent modification
Unsupportedoperationexception object does not support user-requested methods
61st: Throw the exception corresponding to the abstract
    • High-level methods call the lower-level method, and if the lower-layer method throws an exception and the upper-layer method throws the low exception directly, the exception may not be associated with the high-level method, which can be confusing. If the lower-level method modifies the thrown exception, the upper layer is also modified, which destroys the existing client.
    • Higher-level implementations should capture the lower-level exceptions, while throwing exceptions that can be interpreted according to a higher-layer abstraction. This practice is known as abnormal translation. As follows:
// Exception Translation Try {     //  call low-level code catch  (lowerlevelexception e     ) {throw  New  higherlevelexception ();}
    • Special form of exception translation: the anomaly chain. Low-level anomalies are propagated to high-level anomalies, and upper-layer exceptions provide access methods (Throwable.getcause) to obtain lower-layer anomalies. As follows:
// Exception Chain Try {     //  call low-level code catch  (lowerlevelexception e     ) {throw New higherlevelexception (e);}
Cases:
1 /**2 * High-level exception, there is a constructor to accept the exception3 * Created by Itlivemore on 2017/6/25.4  */5 classHigherlevelexceptionextendsException {6      Publichigherlevelexception () {7     }8 9     //constructors that accept exceptionsTen      Publichigherlevelexception (Throwable cause) { One         Super(cause); A     } - } -  the /** - * High-level exception, no constructor to accept exception -  */ - classHigherLevelException2extendsException { + } -  + /*Low Level exception*/ A classLowerlevelexceptionextendsException { at      Publiclowerlevelexception (String message) { -         Super(message); -     } - } -  - classLower { in     Static voidFintParamthrowslowerlevelexception { -         Throw NewLowerlevelexception ("parameter" + param + "call F () exception"); to     } + } -  the /** * * Abnormal chain $ * Created by Itlivemore 2017/6/25.Panax Notoginseng  */ -  Public classExceptionchain { the      Public Static voidMain (string[] args) { +         Try { A call1 (); the}Catch(higherlevelexception e) { + e.printstacktrace (); -         } $         Try { $ call2 (); -}Catch(HigherLevelException2 e) { - e.printstacktrace (); the         } -     }Wuyi  the     Private Static voidCALL1 ()throwshigherlevelexception { -         //there is a constructor that runs the exception chain, the exception is placed in the constructor method Wu         Try { -LOWER.F (1); About}Catch(lowerlevelexception e) { $             Throw Newhigherlevelexception (e); -         } -     } -  A     Private Static voidCall2 ()throwsHigherLevelException2 { +         //constructors that do not run the exception chain, use Initcause () to set the cause the         Try { -LOWER.F (2); $}Catch(lowerlevelexception e) { theHigherLevelException2 exception =NewHigherLevelException2 (); the Exception.initcause (e); the             Throwexception; the         } -     } in}
    • The best way to handle low-level exceptions is to avoid throwing exceptions, such as higher levels to check for parameters before calling lower layers to ensure that the lower execution succeeds. If the exception is not avoided, the upper layer can bypass the exception and log the exception only to troubleshoot the problem.
62nd: Each method throws the exception to have the document
    • Always declare the exception being inspected individually, and use Javadoc's @throws tag to accurately record the conditions under which each exception is thrown. A method may throw multiple exceptions, not declared as "throws Exception".
    • For non-inspected exceptions, record them in the @throws label and do not declare them in the throws of the method.
    • If many of the methods in a class throw the same exception for the same reason, you can create a document in the document comment for that class for that exception. If the input parameter is empty, NullPointerException is thrown.
63rd: Include messages that can catch failures in the detail message
    • The system prints the exception stack trajectory when the program fails due to an uncaught exception, and the ToString method of the exception is called, so the ToString method of the exception returns information about the cause of the failure as much as possible.
    • In order to capture the failure, the details of the exception should contain all the parameters that contribute to the exception and the value of the field.
    • To ensure that the exception's detail message contains enough information to capture the failure, one approach is to introduce these messages in the exception constructor instead of the string detail message. If Indexoutofboundsexception has public indexoutofboundsexception (int lowerbound,int Upperbound,int index) such a constructor.
64th: Strive to keep the atom of failure
    • Failed Atomicity: Failed method calls should keep the object in the state before it was called.
    • Ways to achieve atomic failure
    1. Design an immutable object. If the object is immutable, the atomic nature of the failure is obvious.
    2. Check the validity of the parameters before performing the operation.
    3. Adjusts the order of the calculation process so that any part of the calculation that might fail occurs before the object state is modified.
    4. A infrequently used practice, primarily for permanent (disk-based) data structures. The practice is to write a recovery code that intercepts the failures that occurred during the operation and causes the object to roll back to the state before the operation started.
    5. Performs an action on a temporary copy of an object, and then replaces the object's contents with the results from the temporary copy when the operation is complete.
    • Not conducive to the realization of a failure atomicity:
    1. Multiple threads without the proper synchronization mechanism, the same object is modified concurrently.
    2. For some operations, there is a significant increase in overhead or complexity.
    • Any exception that is generated should keep the object in the state before the method call. If this rule is violated, the API documentation should clearly indicate what state the object will be in.
65th: Do not ignore exceptions
    • Methods to ignore Exceptions: surround the method with a try block and include an empty catch block
// Ignore Exception Try {//  call method catch  (Exception e) {}
    1. If you can ignore the exception, the catch block should contain a description that explains why you can ignore the exception.
    2. Do not ignore exceptions, it is wise to record exceptions.

[Reading notes] "effective Java" 9th Chapter exception

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.