|
1. What is unusual
Poorly structured code can not run, which is the basic concept of Java.
Ideal time to discover the error is at compile time. However, the compiler can not find all the bugs, we need to resolve the remaining issues in the program is running. This requires some way of error, to pass appropriate information to a particular receiver processing. Purpose Java Exception handling is by using a small amount of code to simplify the generation of large, reliable programs, and in this way to get your application in no unhandled errors, but it also brings a significant benefit: reduce error processing complexity of the code.
Exception, according to the literal meaning, the meaning of an accident. It was placed to understand the code level, which prevents the current method or scope to continue.
In Java, exceptions are treated as objects to handle, which is the base class Throwable.
2, the Java exception type
Java directly derived from Throwable Exception and Error. Exception is the basic type which can be thrown in the Java class libraries, methods and runtime failure may throw Exception abnormalities; Error represents compile-time and system errors. Exception class hierarchy
Typical RuntimeException include NullPointerException, IndexOutOfBoundsException, IllegalArgumentException, etc; non RuntimeException include IOException, ClassNotFoundException like.
And according to the way the compiler checks division, can be divided into abnormal checked exceptions (CheckedException) and unchecked exceptions (UncheckedException). Error and RuntimeException collectively referred UncheckedException, the reason why so called because the compiler does not check whether the method or process both types of exception thrown, resulting in this type of exception during compilation is not given, the default by the virtual machine provides treatment. In addition to these two types of Error and RuntimeException exception, other exceptions are called Checked exceptions.
3, Java how to handle exceptions
3.1 try-catch, try-finally, try-catch-finally
For checked exception type, we either deal with it or use throws throws in the method header.
public static void createFile () throws IOException {
File file = new File ( "C: /test.txt");
if (! file.exists ()) {
file.createNewFile ();
}
}
public static void main (String [] args) {
try {
createFile ();
} Catch (IOException ex) {
// Handle exception here
}
}
About catch points to note:
1), abnormal type parameter must be Throwable class or subclass.
2), down from the catch phrase, it must follow the parameter types from the sub-class to the parent class order, because once matched to a type, it will ignore subsequent catch. For example IOException must be placed in front of Exception, otherwise the compiler will complain.
3), there may be one or more catch statements, even if there is finally under statement, the statement can not catch, such as try-finally.
Want to catch multiple exceptions, you can use multiple catch statements, provides another way JDK7 later: Multiple capture (multi-catch).
try {
// Other code
} Catch (IOException | SQLException ex) {
throw ex;
}
4) Do not ignore the exception. Empty catch block exception will achieve their purpose, unless such close FileInputStream time, because you do not have to change the status of the file, so you do not perform any recovery action, and has been read from the file to the desired information , so it does not terminate an ongoing operation.
About finally points to note:
1), finally the code is always executed, except when the try or catch statement VM exit (System.exit (1)).
2), finally block can do some cleanup work resources, such as closing a file, close the cursor operation.
3), finally block is not necessary.
In addition, if the try and finally block executes a return statement, the final returns will be finally the return value.
3.2 Exception chaining
Often they want to catch an exception after another exception is thrown, and you want to preserve the original exception information, which is the exception chain. In JDK1.4 later, Throwable subclass constructor can accept a cause object as a parameter representing the original exception, the original exception is passed through to this new exception, so that even if you create and throw a new exception in the current location, but also through the exception chain to track the location of abnormality occurred first.
But Throwable subclass, only Error, Exception, RuntimeException exception class provides three constructors with parameters cause other types of exceptions you need initCause () method. Such as the definition of the CustomException class, you can use:
CustomException cmex = new CustomException ();
cmex.initCause (new NullPointerException);
throw cmex;
As a result, CustomException inherited from Exception or RuntimeException, belongs to a custom exception.
Generally speaking, the role of custom exception of the following circumstances:
1), the checked exceptions into non-checked exceptions.
2) when an abnormal context information package, defined exception code, collect objects environment, conducive to the transmission of information.
4, abnormal Guide
1) In the case of know how to deal with only an exception.
2), custom exception type, in order to encapsulate all checked exceptions.
3), at the boundary of the program abnormal capture. The service ends of the respective client's request, at the exit of the catch may have internal abnormalities, and unified throw a package over the exception to the client, so that sensitive information is exposed server.
4), used only exception for extraordinary circumstances. Do not habitually use try-catch in all of the code, because this will affect the performance.
5), relatively abstract thrown exception. If the method throws an exception and the task it performs no obvious connection, this situation will make people confused. To avoid this problem, we should achieve a higher level of low-level exception catch, and throw out can be interpreted in accordance with the abnormal level of abstraction, a practice known as exception translation (exception translation), as follows:
try {
// Use lower-level abstraction to do our bidding
} Catch (LowerLevelException ex) {
throw new HigherLevelException (...);
}
Another special exception called translation exception chain, as has been described above. If the low-level exception for debugging problems cause abnormal rise very helpful, it is appropriate to use exception chaining. High-level exception provided access method (Throwable.getCause) to obtain a low-level exception.
6) each have an exception thrown document describes. Use the Javadoc @throws tag for each record throw exception conditions. If a method can throw multiple exceptions, do not use a superclass of these exception classes. Do not declare such a method "throws Exception" or "throws Throwable", which will not have any guidance. |
|
|
|