Common Java exception handling

Java programs are abnormal problem often encountered, an exception is a Bug, it would take a lot of time to locate anomalies.
Java exceptions
(1) Throwable Java exception is top class, all exceptions inherit from this class.
(2) Error, Exception are two major categories of exception classes.
(3) Error exception non-program, i.e. the program can not be caught exceptions, generally compiled or systematic errors, such as memory overflow OutOfMemorry abnormal.
(4) Exception class program exception is generated by an internal program. Abnormal, abnormal non-operating Exception divided into runtime.
(5) Features runtime exception is Java compiler does not check it, that is to say, such an exception may occur when the program even without a try-catch statement catches it, throws clause declared useless throw it It will compile, can not handle abnormal operation or handling. Often abnormal out generally defined custom system abnormal operation, the abnormal traffic is processed differently according to custom. NullPointException common abnormalities such as running, ArrayIndexOutOfBoundsException and so on.
(6) non-runtime exception is exception handling procedures must be carried out, capture or throw, if the handler does not compile. Such as the common IOException, ClassNotFoundException and so on.
Common Java exception pits
the toughest pit --NullPointerException
null pointer exceptions should be every programmer has to step on the pit was, is and should continue to regularly step on step on the pit, widespread and extremely difficult to eradicate. But the pit can be effectively prevented by some means.
(1) What is the null pointer?
When a variable value is null, which represents the empty object in Java that does not exist, no actual content, there is no memory allocation default, the object is null member variables to it.
So, if an object is not initialized operation, this time, if you call this method or variable object, there will be a null pointer exception.
The following example will null pointer exception occurs:
Object Object = null;
String String = Object.toString ();
null pointer it belongs to a subclass RuntimeException runtime, it is not captive, and may run only when Report out, but will also cause a program interruption.
How to avoid a null pointer?
Here is what I encountered in the encoding process, problems and solutions.
String comparison, constants placed in front --- always equals call from a known non-empty String object () method of
IF (status.equals (SUCCESS)) {
}
This time status may cause abnormal null pointer is null, should constant put in front, be able to avoid a null pointer exception. This should be developed in a variety of specifications which will be referred to, it is the most basic.
IF (SUCCESS.equals (Status)) {
}
When valueOf () and toString () returns the same result would prefer to use the former.
Because the call toString null object () throws null pointer exception, if we can use valueOf () to get the same value, that would rather use valueOf (), passing a null to valueOf () will return "null", in particular in those packaging, like Integer, Float, Double, and BigDecimal.
BD = the getPrice the BigDecimal ();
System.out.println (String.valueOf (BD)); // throws a null pointer exception does
System.out.println (bd.toString ()); // throw a NullPointerException
initialization defaults values
give it a default value when object initialization or default constructor implemented, such as:
the User User new new = the User ();
String name = StringUtils.EMPTY;
avoid returning empty collection
returns a collection, the default will be null, standardized It returns an empty set.
For example, List, such as:
public getUserList List () {
    List List userMapper.gerUserList = ();
    return null new new List the ArrayList == ():? List;
}
so that the receiver would have to worry about the null pointer exception, not affect business.
Using new features JDK8 Optional
 Optional Jdk8 is provided a container object can contain a null value, it may be used instead xx! = Null is determined. (The temporary lane system because our uniform application is Java7, this program has not been used to the system code in the car.)
OutOfMemoryError
Exceptions Exception Bug memory is a frequent, but this is not a program that can be controlled, the problem is simply more memory allocated objects beyond the current maximum heap memory, you need to adjust the heap size (-Xmx) and optimization program.
(1) Common following reasons:
the amount of data loaded in memory 1 is too large, too much data as extracted from a database;
2. collection class has not emptied after use references to objects, such JVM may not be recovery;
dead cycle or repeating cycle of excessive physical presence of the object 3. code;
third-party software in 4. BUG;
5. the start value is set too small in the parameter memory
(2) common solution:
1. application server prompts the wrong solution:
  the startup parameter memory value large enough.
2.Java code that caused the error to solve:
whether there is an infinite loop or a recursive call 1) Check the code.
2) Check for a cycle repeatedly generating new object entity.
3) Check the database query, if there is a query to get all the data. In general, if one takes thousands of records into memory, it may cause memory overflow. This problem is rather hidden in the front of the line, less data in the database, not easy problems, on the line, more data in the database, a query is likely to cause memory overflow. So the query to the database query maximize the use of paging.
4) Check List, MAP collection object and so there after use, the problem is not clear. List, MAP collection object and so there will always be a reference to the object, so that these objects can not be recovered GC.
IOException
IO, namely: input, output, we In a read and write disk files, web content when students often abnormal, this anomaly is inspected anomaly, the need for manual capture. There are two commonly used exception handling, one is: Use throws throws an exception may occur, and the other is: direct try-catch.
ClassNotFoundException
class can not find an exception, Java developers often encountered, is not so desperate? This is the time to load the class thrown out, that can not load the specified class in the class path.
Note: not recommended for use in lane throws an exception thrown to the program processing system, lane system to be able to capture all captured exception handling, an exception occurs when the purpose of the program level to ensure that the program can driveway normal fee, because the program can not be an exception the ongoing impact of the charging process.
General principles of exception handling
1, early treatment can handle it, do not throw an exception and finding ways to deal with can not digest, or converted to handle RuntimeException. Because for an application system, it throws a number of exceptions is problematic, it should control the possible exception of program development from the perspective possible.
2, for the abnormalities, if the process is not effective, not as converted to RuntimeException thrown. This also allows room for the upper code selective - can handle or not handle.
3. For an application, it should have its own set of exception handling framework, so that when an exception occurs, the process can be unified style, elegance abnormal feedback to the user.
Translation and unusual anomalies chain 
 1, abnormal translation of the principles of 
the so-called abnormalities translation is an unusual convert to another new exception, perhaps more accurately this new abnormal expression of abnormal procedure occurred.
There is a reason the concept is abnormal, the abnormal causes of the thrown exception object that unusual, abnormal constructor that takes almost all causes of abnormal use of type Throwable as arguments in Java, which also provides direct support for abnormal translation because any form of anomalies and errors are a subclass of Throwable. For example, to convert to another SQLException a new exception DAOException, could write:
    to customize an exception DAOException:
   for example, there is a type of the exception object SQLException e, to be converted to DAOException, you can write:  
public class DAOException the extends RuntimeException {
// (not part of the code)
public a DAOException (String Message, Throwable the cause is) {
super (Message, the cause is);
}
}
a DAOException daoEx = new new a DAOException ( "the SQL abnormal", e);
abnormal translation is for the class of all inherited Throwable superclass terms, programming syntactically speaking, can be converted each other subclasses. However, rationality and system design point of view, an exception can be divided into three categories: Error, Exception, RuntimeException.
 Exception handling there is a philosophy: application for a system, any system anomalies or errors that occur for users who are operating within the system "run-time" exception, all the application system abnormalities. This is also the guiding principles and abnormal abnormal translation application framework system design. A lot of processing AxiTrader rebate www.fx61.com/brokerlist/axitrader.html negative impact of non-checked exceptions in the system a lot, the most important aspect is to reduce the readability of code, programming complex exception handling code is also very pale weakness. Therefore, it is necessary to check these anomalies and errors Exception Error converted to a RuntimeException, so programmers under the circumstances to decide whether to capture and handle exceptions that occur.
①: Error to Exception: Conversion errors as abnormal, and continue to throw. E.g. Spring WEB framework, the org.springframework.web.servlet.DispatcherServlet of the doDispatch () method, the error translates a captured NestedServletException exception. The aim is to restore order to maximize the negative impact brought about by errors. Error is often because of a very serious mistake, it may cause the system to hang.
②: Exception to RuntimeException: checks exception into RuntimeException allows program code to become more elegant, allowing developers to focus on a more rational design of program code, which in turn increases the likelihood of occurrence of abnormal system.
③: Error to RuntimeException: the purpose is still the same. All the exceptions and errors translates into no abnormalities, so you can make the code more concise, and help unify the handling of errors and exceptions information.
1, abnormal strand
cause of abnormal chain name suggests is a cross abnormality occurs a string together, i.e., the abnormality information is transmitted to the upper layer underlying such layer by layer thrown. Java API documentation gives a simple model: 
the try {
lowLevelOp ();
} the catch (LowLevelException Le) {
the throw (HighLevelException)
new new HighLevelException () the initCause (Le);.
}
when the program captured a bottom exception le, the processing section selects a higher level to continue to throw new exception to the caller of this method. The reason for this anomaly will transfer layer by layer. In this way, on the upper floors of abnormal recursive call getCause () method, you can traverse the reason for the exception of the layers. This is the principle Java exception chain. The practical application of the exception chain of small, throw an exception occurs when the layer by layer is not a good idea, these anomalies can get the upper Nai Ho? And abnormal layer by layer on the cast will consume a lot of resources, because you want to save a complete anomaly chain information.

Guess you like

Origin blog.51cto.com/14511863/2444114