20190901 On Java8 Chapter XV abnormal

Chapter XV abnormal

To create a robust system, each of its members must be robust.

Abnormal concept

C ++ exception handling mechanism based on Ada, Java exception handling in C ++ is built on the basis of the above (even though it looked more like Object Pascal).

The basic abnormality

Abnormal parameters

All standard exception class has two constructors: one is no argument constructor; another character string is accepted as a parameter to the constructor of the exception object into information can.

Throwable Is the root class exception type.

Custom exception

Abnormal, the most important part of the class name.

Anomalies and logging

For the exception classes, the getMessage()approach is somewhat similar to the toString()method.

Abnormal statement

However, there are a can "cheat" place: You can declare method will throw an exception, in fact, not thrown. The compiler believe this statement, and force users to really like this method throws an exception that use this method. The advantage of this is that abnormal pre-emption seats, since you can throw this exception without modifying existing code. This capability is important when defining the abstract base classes and interfaces, so that the derived class or interface can throw an exception these pre-declared.

Catch all exceptions

Multiple capture

By Java 7 multiple capture mechanism may use different types of abnormality "or" combine them, only in a catchuse block:

try {
    x();
} catch (Except1 | Except2 | Except3 | Except4 e) {
    process();
}

Stack traces

printStackTrace()Information provided methods can getStackTrace()be direct access method, which returns an array of elements in the stack trace configuration, wherein each element represents a stack frames. 0 element is the top element, and is the last in a sequence of method calls to call (this Throwableis created and thrown out of office). Bottom of the stack and the last element in the array is to call a method of the first call in the sequence.

Rethrows

Just rethrow the current exception object, then the printStackTrace()method will display the original call stack information points exception is thrown, rather than re-throw points of information. To update this information, you can call the filInStackTrace()method, which will return an Throwableobject that is by the current call stack information that filled the original exception object is established. Call fillInStackTrace()the line would become a new place of the abnormality.

Accurate re-thrown

From Java 7 starts, allowed to throw more specific exception, i.e., the catch is captured by the parent, you can throw catch block subclass.

Abnormal chain

In Throwablesubclass, only three base exception class constructor is provided with a cause parameter. They are Error(for the Java Virtual Machine error reporting system), Exceptionas well RuntimeException. If you want other types of abnormalities linked, you should use initCause0methods rather than constructor.

DynamicFieldsException dfe = new DynamicFieldsException();
dfe.initCause(new NullPointerException());
throw dfe;

Java standard exceptions

ThrowableThis Java class is used to represent anything that can be thrown as an exception class. ThrowableObjects can be divided into two types (refer to the Throwabletype inheritance obtained): Errorused to indicate a compile-time error and the system (except in special circumstances, you generally do not care about); Exceptionthe basic types can be thrown in the Java class libraries , methods, and user runtime failure might throw Exceptionexceptions. Therefore, the base type of Java programmers concerned usually Exception.

The basic concept is unusual problems that occur with name represents, and the name of the exception should be able to look to know Italian culture. Not all anomalies in the java.langpackage defined; is used to support some other abnormal image util, net and io such packages, these anomalies or can be discerned from their parent class by their full name.

Exceptions: RuntimeException

RuntimeExceptionType of exception (or from any RuntimeExceptioninherited abnormality), also known as " unchecked exception ." This abnormal type of false, on behalf of the programming error and will be automatically captured.

Only ignored code RuntimeException(and its subclasses) type of exception, since all the examined type of exception processing is enforced by the compiler.

Abnormal restrictions

When covering methods can throw only those exceptions listed in the exception description of the method in the base class.

Abnormal limit configuration does not work.

Exception description appears in a base class methods of abnormal, or may not appear in the exception specification in the derived class method. This is significantly different from the same inheritance rules, in succession, the base class must appear in a derived class, in other words, in the process of inheritance and coverage, the "exception specification interface to" a particular method is not large a smaller but - and this is exactly the case when the class interface inherited opposite.

Try-With-Resources Usage

Java 7 introduces try-with-resourcessyntax.

In the try-with-resourcesobject created is defined in clause (in parentheses) must implement the java.lang.Autocloseableinterface that has a method, close (). When introduced in the Java 7 AutoCloseable, the number of interfaces and classes are modified to implement it; see the Javadocs AutoCloseable, can find a list of all classes that implements the interface, including Streamthe object.

Each object specification defined header will be called after the try block operation close()method.

The Java 5 Closeablehas been modified, the interface after revision inherited AutoCloseableinterface. So all implementations of Closeableobject interface, supports the try-with-resourcesfeature.

You can not define a resource specification is not in the header AutoCloseableof the object.

Abnormal match

When thrown, the exception handling system will find the "nearest" handlers in the writing order code. After finding the matching processing program, it is believed an exception would be addressed, then look no further.

When looking for does not require an exception handler with the exceptions thrown exact match declared. Derived class objects can also match its handler base class.

Other alternatives

Exception handling is an important principle is "only catch exceptions in you know how to handle the situation."

All models are wrong, but some are usable.

Good programming languages ​​to help programmers write a good program, but can not avoid no matter what language programmers use it to write a bad program.

Abnormal Guide

You should use exceptions in the following situations:

  1. Use as much as possible try-with-resource.
  2. Deal with the problem at the right level. (In the case of know how to handle it catch the exception.)
  3. Solve problems and recall method produces abnormal.
  4. Make minor repair, and then continue to bypass local exception occurred.
  5. Calculated using other data, in place of the method of the expected value is returned.
  6. To do as much as possible under the current operating environment things done, then the same exception thrown weight higher level.
  7. To do as much as possible under the current operating environment things done, then the different exceptions thrown into a higher level.
  8. Terminate the program.
  9. Simplified. (If you have abnormal pattern make the problem becomes too complicated, and that using them would be very painful and very annoying.)
  10. Let library and program safer. (This is both in short-term investment for debugging to do, it is to do long-term investment for the robustness of the program.)

Guess you like

Origin www.cnblogs.com/huangwenjie/p/11442034.html