The view of abnormal handling (reprint)

Source: Internet
Author: User
Tags constructor error handling exception handling functions garbage collection memory usage
Exception handling in Java programming is a common topic, and almost any introductory Java course mentions exception handling. However, I think a lot of people actually do not really master the correct way to deal with abnormal situations and strategies, at most, but also know the approximate point of view. In this paper, three kinds of different degrees and quality of the Java exception processing are discussed, the treatment of abnormal methods are divided into: good, bad and bad three kinds. It also gives you some tips on how to solve these problems.


Good


exception Handling provides a uniform mechanism for handling program errors. In fact, the Java language significantly improves the ability of exception handling in software development by presenting an exception warning to callers. This approach extends and enhances the method in the Java language to include its own error conditions. Let's take a look at an example that illustrates this situation.


The following is the prototype of one of the FileInputStream constructors:


public FileInputStream (String name) throws FileNotFoundException


this prototype and C or C + + language of similar prototype are not the same, Java methods and constructors must declare that they may be "thrown out" when the exception, the use of the keyword is "throws." This exception hint in the method prototype increases the reliability of the program. Obviously, this approach prompts the caller of the method for possible exception conditions so that the caller can appropriately handle the exceptions.


The following code to indicate how we captured and handled the FileNotFoundException exception:


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 has some other excellent features, such as checking for exceptions, user-defined exceptions, and the new Java logging APIs (Java Logging APIs) that are launched in JDK 1.4.

All subclasses of
java.lang.Exception belong to a check exception. The check exception (checked exception) is the exception that must be prompted by the method that throws the exception, which must be caught or prompted to the caller.

The
user-defined exception (user-defined exceptions) is a custom exception class that extends the Java.lang.Exception class. Excellent Java programs stipulate custom exception encapsulation, reporting, and handling of their own unique situations. The latest Java Record API (Logging API) allows you to centralize the recording of exceptions.


is not good

The bad side of
Java exception handling includes two cases: misuse of unchecked exceptions (unchecked exceptions) and misuse of catchall constructors. Both of these ways make the problem complicated.


there is a class of exceptions that belong to the RuntimeException subclass, and this exception is not checked by the compiler. For example, NullPointerException and arraystoreexception are examples of this type of exception. Programmers can subclass RuntimeException to avoid checking for exceptions, so that the methods that produce them are used by their callers. A professional development team should allow only a very small number of cases to do so. The 2nd type of exception handling is the Catchall builder. The so-called "Catchall constructor" is an exception capture code module that can handle all the possible exceptions thrown at it.


The following is an example of a catchall processor:


Try


{


Code here with checked exceptions


} catch (Throwable t)


{


T.printstacktrace ();


}


I have to admit that I used this technique when I was writing a generic program, but this type of constructor must be avoided when writing key programs, unless they are authorized to use it in conjunction with a central error processor. In addition, the Catchall constructor is only a mechanism for speeding up programming progress by avoiding error handling.

A disadvantage of
exception handling is that it is difficult to adopt good error handling strategy. Exceptions such as recovery from a low capacity memory state, write errors, and algorithm errors are not easily resolved. You can try the usual techniques of recycling, garbage collection, and alerting users to cope with the situation.


Bad


and many Java features and their APIs are similar to the Java exception handling mechanism also has the "Overlord Hard bow" category of funny mistakes. For example, in order to throw out an exception and not hesitate to use the "new" keyword for its allocation of memory is the case. I don't know how many times I've been hit by a serious compiler because I made this mistake. In this case, we are actually serving the language rather than making the language work for us.


in the Java pitfalls Book I wrote, I explored several flaws in exception handling, such as dealing with outofmemoryerrors. The process is to use the finally module to close the file and parse the exception to get the method and line of code that the problem occurs. The biggest flaw in this process is the need to capture OutOfMemoryError, which is not an anomaly to check! Consider that memory exhaustion is a fairly common situation. Any program that is closely related to the memory usage status should capture and handle this error.


Finally, let's consider two features that are not yet part of the Java exception handling mechanism. First, the current situation is that after you successfully handle the anomaly, you can't go back to where you just left off. The C-language setjmp () and longjmp () functions can implement this feature, Java should have the corresponding version of these two functions, and we should be able to use the "resume" keyword to achieve it.


The second feature that is not implemented is the global exception handler, which is the Set_new_handler () in the C + + language. For example, when programming, even though outofmemoryerror exceptions are more common than java.lang.Error subclasses, we can also use global processors for OutOfMemoryError exceptions. Such an effect would be much better than using the usual check exception for it. If you feel very concerned about these features, then you can make your own suggestions in the Java Developer Connection: Add these features to the Java platform!





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.