"Effective Java" 9th Chapter exception

Source: Internet
Author: User
Tags throwable

58th: Use the exception for recoverable cases, use run-time exceptions for programming errors

The Java programming language provides three types of throwable (checked exception) runtime exceptions (Run-time exception) and errors (error).

the exception being inspected is a potential indication
The main principle when deciding whether to use a inspected exception or an exception that is not examined is if you expect the caller to be able to properly recover the exception that should be used for this situation. Forces the caller to handle the exception in a catch clause by throwing the inspected exception. or spread it out. Therefore, each inspected exception that is declared to be thrown in the method is
A potential indication to the API user that the condition associated with the exception is a possible result of invoking the method.
IOException、SQLException

using Run-time exceptions to indicate programming errors
There are two types of non-inspected, thrown structures: run-time exceptions and errors. The two are identical in behavior: they are both unwanted and should not be caught in a thrown structure. If a program throws an exception or error that is not being examined, it is often a non-recoverable situation and it is detrimental to continue execution. If the program does not catch such a thrown structure, it will cause the current thread to stop (halt) and an appropriate error message appears.

 
   
  
  1. Java lang arithmeticexception
  2. java lang classcastexception
  3. java lang illegalargumentexception
  4. java lang indexoutofboundsexception

Although the JL5 (Java language Specification) is not required, by convention, errors are often reserved by the JVM to indicate insufficient resources, constraint failures, or other conditions that make the program unable to continue execution. Since this is an almost universally accepted practice, it is best not to implement any new error subclasses. Therefore, all of the non-inspected throw structures you implement are
Should be a subclass of runtimeexception (direct or indirect).

The designer of the API often forgets that an exception is also an object in its full sense, and that it can define arbitrary methods on it.

Because the exceptions that are inspected often indicate recoverable conditions, it is particularly important to provide some helper methods for such exceptions, in which the caller can obtain some information that will help with the recovery. For example, suppose that because the user did not store a sufficient amount of money, he attempted to make a call on a toll phone and would fail, thus throwing out the exception to be inspected. This exception should provide an access method that allows the customer to query for the missing fee amount, which can be passed to the telephone user.

    • Resources
      "1" [Java examined exception and non-inspected exception]http://blog.csdn.net/nlznlz/article/details/53271045
      "2" [Java Runtime exception and non-runtime XOR] (
      http://blog.csdn.net/huhui_cs/article/details/38817791)
61st: Throw the exception corresponding to the abstract

Exception Translation
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 Exception translation (exception translation), as follows:
The following example of exception translation is taken from the Abstractsequentiallist class:

Exception Chain
A special form of anomalous translation is called an anomaly chain (exception chaining), and it is appropriate to use an exception chain if the lower-level exception is very helpful for debugging problems that result in a high layer exception. The lower-level anomaly (cause) is passed to the upper layer of the exception, and the high-level exception provides the Access method (Throwable.getcause) to obtain the lower exception:

Support Chain
The top-level exception constructor passes the reason to the support chain (Chaining-aware) Super-constructor, so it will eventually be passed to one of Throwable's constructors that runs the exception chain, such as Throwable (Throwable):

Most of the nonstandard exceptions have constructors that support chains. For exceptions that do not have a support chain, you can use the Throwable Initcause method to set the cause. The exception chain not only allows you to access the cause through the program (with Getcause), it also integrates the cause's stack trajectory into higher-level exceptions.

64th: Strive to keep the atom of failure

In general, a failed method call should keep the object in the state before it was called. A method with this property is known to have failed atomicity (failure atomic).

Immutable Objects
There are several ways to achieve this effect. The simplest way is to design an immutable object.

variable objects are checked before execution
For methods that perform operations on mutable objects, the most common way to obtain failed atomicity is to check the validity of the parameters before performing the operation (see 38th). This allows the appropriate exception to be thrown before the state of the object is modified.

If you cancel the check of the initial size (size), it will still throw an exception when the method attempts to eject the element from an empty stack. However, this will cause the size field to remain in an inconsistent state (negative number), causing any future method calls to that object to fail.

Write Recovery Code
The third way to get a failed atom is far less common, by writing a recovery code that intercepts the failure that occurred during the operation and recovery the object back to the state before the operation began. This approach is primarily used for permanent (disk-based (disk-based)) data structures.

Temporary Copy
The last way to get the atomic failure is to perform an operation on a temporary copy of the object. When the operation is complete, replace the contents of the object with the results from the temporary copy.
For example, before Collections.sort performs a sort, it first takes its input list to an array in order to reduce the overhead required to access elements in the inner loop of the sort. This is a performance-based approach, but it adds an advantage: even if the sort fails, it ensures that the input list remains intact.

Errors (as opposed to exceptions) are often unrecoverable, and when methods throw errors, they do not need to attempt to maintain the atomicity of failure.

"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.