Deep understanding of the pros and cons of exception handling in Java programming _java

Source: Internet
Author: User
Tags error handling exception handling garbage collection memory usage readline try catch
Exception handling in Java programming is a common topic, and almost any introductory Java course will mention exception handling. However, I think a lot of people do not really grasp the correct way to deal with abnormal situations and strategies, at most, but also understand the concept of the idea. I want to discuss three different levels and quality of Java exception handling, described in the manner of handling the exception is divided into:
good, bad and bad three kinds.
It also provides some skills to solve these problems.
First, explain some definitions and mechanisms that must be clarified in Java exception handling. Any violation that derives from the error class or the RuntimeException class is referred to by the Java language specification as an "Unchecked" exception, and all other exceptions are called "verifiable" (Checked) exceptions.
The so-called inspection anomaly refers to the exception that we should handle ourselves. As for the means of handling, either control (try catch) or notice (throws) they are likely to produce. In general, you should catch those exceptions that you know how to handle, and advertise those exceptions that you do not understand how to handle.
And for those that cannot be checked, they are either outside our control (Error) or we should not allow it first (runtimeexception).
As for the exception designation, the Java rule is very simple: a method must notify itself of all possible check exceptions that may be generated. When writing your own method, it is not necessary to notice every exception object that the method is actually likely to produce, and to understand when you have to throws the method to advertise the exception, you must know that for an exception, He can only produce in the following four situations :
1. A method that may produce an exception is invoked. For example, the ReadLine method of BufferedReader class. This method informs Java.io.IOException exceptions
2. An error was found and an exception was generated with the throw statement.
3. A programming error has occurred. For example A[-1] = 0.
4.Java An internal error has occurred.
If you have one of the first two cases, you must tell the person who intends to use your method: If you use this method, you may create an exception (that is, use throws on the method head), a simple memory method:
As long as contains throw, it is necessary to notify throws. If a method must handle multiple exceptions at the same time, all exceptions must be indicated within the header.
As shown in the following example, divide them by commas:
Copy Code code as follows:

Class Animation
{
Public Image LoadImage (Strint s) throws Eofexception,malformedurlexception
{
......
}
}

However, we do not need to advertise internal Java errors and should not advertise exceptions derived from RuntimeException.
Good exception handling
Good exception handling provides a uniform mechanism for handling program errors. In fact, the Java language dramatically 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 a prototype of one of the FileInputStream constructors:
Public FileInputStream (String name) throws FileNotFoundException Java
Methods and constructors must declare that they may "throw out" the exception when they are invoked, using the keyword "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 signals how we caught and handled the exception of FileNotFoundException:
Copy Code code as follows:

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 other excellent features, such as checking for exceptions, user-defined exceptions, and the new Java logging APIs (Java Logging APIs) that are introduced 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. User-defined exceptions (user-defined exceptions) are custom exception classes that extend 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. Bad Java exception handling
The bad side includes two kinds of situations: misuse of unchecked anomalies (unchecked exceptions) and misuse of catchall constructors. Both of these ways make the problem complicated.
There is a category 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 second 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 are examples of catchall processors:
Copy Code code as follows:

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.
One disadvantage of exception handling is that it is difficult to adopt an excellent 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.
the Bad treatment method
Like many Java features and their APIs, the Java exception handling mechanism also has a ludicrous error of the "Overlord on the Bow" category. 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. And the outofmemoryerrors we encounter is the flaw of exception handling. This process is:
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.
Some suggestions for using exceptions
1. The design purpose of exception control is not to replace some simple tests. Use exceptions only in exceptional circumstances!
2. Do not refine the anomaly excessively. Instead of adding exception handling on each statement, it's a good idea to put the entire task in a try block. If one of the operations fails, you can discard the task immediately.
3. Do not "suppress" the exception. For the methods that need to advertise the exception, we can use the capture method to force the exception to shut down, if there is a real exception, the exception will be "quiet" ignored. If you feel that the anomaly is very important, you must take more effort to control it properly.
4. Don't mind abnormal delivery. If the invoked method produces an exception, such as the ReadLine method, they are naturally able to catch their own possible exceptions, in which case a better way is to pass these exceptions instead of catching them yourself.
Related Article

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.