Sunday, September 5, 2010

Java programming in the way the merits of exception handling

Exception Handling in Java programming is a very common topic, almost any one introductory course will be mentioned Java exception handling. But I think a lot of people have not really master the correct way to handle exceptions and strategies, but most will probably know one, know the point of the concept. In this paper, three different levels and quality of Java exception handling are discussed, the way to handle the exception set out by means of the heights is divided into:

Good, bad and the bad of three.
At the same time to provide you with some techniques to solve these problems. 
First of all, to explain some java exception handling must be clear definitions and mechanisms. Java language specification from the Error class or a class derived from RuntimeException are called unauthorized "non-inspection" (Unchecked) anomaly; all other exceptions are called "to check" (Checked) exception. 

So can abnormalities, is that we should handle their own exceptions. As a means of treatment, or control (try catch), or circular (throws) they may have. In general, how should catch exceptions that are known, but notice that I do not know how to handle the exception. 

To those who can not be abnormal, they are either outside of our control (Error), or is not the permission first (RuntimeException). 

As for the exception specified, Java's rules are simple: a method to notice their possible all the abnormalities. Write your own methods, not necessarily notice the way the real potential of each exception object, in order to understand when the method throws bundle must sentence to notice anomalies, we must know that an exception, he only could In the following four situations will arise: 

1. Call the possible exception of the method. ReadLine method of BufferedReader class instance. Notice that this method Abnormal java.io.IOException 

2. Detected an error and an exception with the throw statement. 

3. The emergence of a programming error. Such as a [-1] = 0. 

4. Java an internal error. 

If one of the first two situations, you must tell the people who intend to use their own method: if using this method may cause an abnormal production (that is, to use his head in the method throws), a simple mnemonic: 

As long as with throw, we should notice throws. If a method must also deal with many exceptions, it must be pointed out first of all exceptions. As the example showed, they were separated by commas:

 1 
2
3
4
5
6
7
 class Animation  

(

public Image loadImage (Strint s) throws EOFException, MalformedURLException

(

... ... ... ...

)

)


However, we do not notice the internal java error, notice should not be derived from RuntimeException exception. 

Good exception handling 

Good exception handling provides a unified mechanism for handling error. In fact, Java, exceptions raised by a warning to the caller by way of significantly improving the software development in the exception handling capabilities. In this way the Java language "method (method)" is extended and enhanced to include its own error conditions. Here we get an example, this example illustrates this situation. 

The following is one of the FileInputStream constructor prototype: 

public FileInputStream (String name) throws FileNotFoundException Java 

Methods and constructors must declare that they may be called "throwing" the exception, using the keyword is "throws". In the prototype of this method of increase in abnormalities appeared programming reliability. 

Obviously, this way the caller to the method suggests possible abnormal conditions, so the caller can take appropriate these anomalies dealt with accordingly. The following code to indicate how we catch and handle this exception FileNotFoundException: 

 1 
2
3
4
5
6
7
8
9
10
11
 try  

(

FileInputStream fis = new FileInputStream (args [0]);

/ / Other code here ...

)

catch (FileNotFoundException fnfe)

(

System.out.println ("File:" + args [0] + "not found. Aborting.");

System.exit (1);

)


Java exception handling, there are other outstanding features, this is can be abnormal, user-defined exceptions, and in JDK 1.4 has introduced a new Java Record API (Java Logging API).java.lang.Exception of all the classes that belong to the abnormalities. May be abnormal (checked exception) is thrown out of the unusual method to prompt the exception, that exception must be caught or prompts to the caller. User-defined exceptions (User-defined exceptions) are custom exception class, exception class that extends the java.lang.Exception class. Java program provides an excellent custom exception package, reports, and deal with their own unique situation. The latest Java Record API (logging API) you can focus on records exception.



Java exception handling bad 

The downside includes two situations: abuse is not abnormal (unchecked exceptions), and the abuse of such catchall constructor. Both approaches make the problem more complicated. 

There is a type of exception is a subclass of RuntimeException, this exception will not be checking compiler. For example, NullPointerException and ArrayStoreException exception is an instance of this type. Programmers can be subclass RuntimeException to avoid the abnormal restriction, which means easy to produce these anomalies used for the caller. 

Professional development team should be allowed only in rare cases can do so. 

The second bad habit is the catchall exception handling constructor. The so-called "catchall constructor" is an unusual catch code module, which can handle all possible exceptions thrown at it.

The following is a catchall processor instance: 


 1 
2
3
4
5
6
7
8
9
 try 

(

/ / Code here with checked exceptions

)

catch (Throwable t)

(

t.printStackTrace ();

)


I have to admit, I have the time in the preparation of the general procedure has been used on this technology; However, the key process in the preparation of a time when this type of constructor must be avoided, unless they are authorized to co-processor and the central error Use it to do so. 

In addition, catchall constructor, but only a by avoiding the error-handling mechanism of the accelerated programming schedule. 

Exception handling of a gap is hard to use good error handling strategy. State of recovery from a low capacity memory, write error and algorithm error such anomalies can not easily be resolved.You can try cycling, garbage collection and to remind the user to deal with more common techniques such as the situation. 

Poor treatment 

And a similar number of Java features and API, Java's exception handling mechanism of "hijacking the" wrong kind of funny. For example, in order to throw an exception even hesitate to use the "new" Key words for allocating memory is one such example. 

I do not know how many times because of committing such a serious error in the compiler before run into a wall repeatedly. In this case, we really are in wait on the language rather than language we use. There we met the OutOfMemoryErrors is exception handling defects. The process is: 

Finally close the file using the module, parsing unusual way to get problems and lines of code. In this process, the biggest flaw of the need to capture OutOfMemoryError, but this exception is not to abnormal! Think about it, memory exhaustion is a common situation. Any use of state of the memory is closely related to the procedure should be to capture and process the error. 

Use exception to some of the recommendations 

1. Abnormal control is not designed to be used instead of some simple tests. Only in exceptional circumstances to use exceptions! 

2. Do not over-refined exception. Do not both with each statement, exception handling, better to try the task on the block. If one has an operation failed, you can then abandon the mission. 

3. Not to "suppress" abnormal. The need to notice unusual way, we can use the method to capture the abnormal forced to close, if unusual, the exception would be "quiet" neglect. If you think that will be very important exception generated, they must charge harder to control it correctly. 

4. Do not mind the unusual delivery. If the method is called an exception, such as readLine 方法, they are born to catch that he might create the exception, in this case, a better way is to these anomalies 传递 Zuofa out, not its own hands Laibuzhuota.

No comments:

Post a Comment