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 catch
use 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 Throwable
is 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 Throwable
object 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 Throwable
subclass, only three base exception class constructor is provided with a cause parameter. They are Error
(for the Java Virtual Machine error reporting system), Exception
as well RuntimeException
. If you want other types of abnormalities linked, you should use initCause0
methods rather than constructor.
DynamicFieldsException dfe = new DynamicFieldsException();
dfe.initCause(new NullPointerException());
throw dfe;
Java standard exceptions
Throwable
This Java class is used to represent anything that can be thrown as an exception class. Throwable
Objects can be divided into two types (refer to the Throwable
type inheritance obtained): Error
used to indicate a compile-time error and the system (except in special circumstances, you generally do not care about); Exception
the basic types can be thrown in the Java class libraries , methods, and user runtime failure might throw Exception
exceptions. 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.lang
package 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
RuntimeException
Type of exception (or from any RuntimeException
inherited 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-resources
syntax.
In the try-with-resources
object created is defined in clause (in parentheses) must implement the java.lang.Autocloseable
interface 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 Stream
the object.
Each object specification defined header will be called after the try block operation close()
method.
The Java 5 Closeable
has been modified, the interface after revision inherited AutoCloseable
interface. So all implementations of Closeable
object interface, supports the try-with-resources
feature.
You can not define a resource specification is not in the header AutoCloseable
of 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:
- Use as much as possible
try-with-resource
. - Deal with the problem at the right level. (In the case of know how to handle it catch the exception.)
- Solve problems and recall method produces abnormal.
- Make minor repair, and then continue to bypass local exception occurred.
- Calculated using other data, in place of the method of the expected value is returned.
- To do as much as possible under the current operating environment things done, then the same exception thrown weight higher level.
- To do as much as possible under the current operating environment things done, then the different exceptions thrown into a higher level.
- Terminate the program.
- Simplified. (If you have abnormal pattern make the problem becomes too complicated, and that using them would be very painful and very annoying.)
- 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.)