The pros and cons of Java exception handling

Source: Internet
Author: User
Tags try catch

Exception handling in Java programming is a common topic, and almost any introductory Java course will refer to exception handling. However, I think a lot of people do not really grasp the correct handling of the abnormal situation of the methods and strategies, at most, but also know a general, know the concept. I want to discuss three different degrees and qualities of Java exception handling, and the way of handling exceptions is divided into:

Good, bad and bad three kinds.

It also provides some tips for solving these problems.

First, explain some definitions and mechanisms that must be clarified in Java exception handling. Any violation that is derived from the error class or RuntimeException class by the Java language Specification is referred to as a "non-checked" (unchecked) exception, and all other exceptions are referred to as "check-in" (Checked) exceptions.

The so-called check exception refers to the exception that we should handle ourselves. As for the means of processing, either control (try Catch) or advertise (throws) they are likely to produce. In general, you should catch exceptions that you know how to handle, and advertise exceptions that you do not understand how to handle.

For those who cannot check for exceptions, they are either outside our control (Error), or we should not be allowed first (runtimeexception).

As for exception designations, the Java rules are very simple: a method must advertise all of the possible check exceptions that it might produce. When writing your own method, it is not necessary to advertise every exception object that the method actually produces, and to understand when it is necessary to advertise the exception with the throws bundle of methods, you must know that for an exception, he can only produce in the following four cases:

1. Called a method that could produce an exception. such as the ReadLine method of the BufferedReader class. This method advertises the java.io.IOException exception

2. An error was found and an exception was generated with the throw statement.

3. A programming error has occurred. such as a[-1] = 0.

4.Java generates an internal error.

If you have one of the first two cases, you must tell the person who intends to use your own method: If you use this method, it can result in an abnormal generation (that is, using throws on the method head), a simple memory method:

As long as there is a throw, you should 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, they are split with commas:

1234567    class Animation    {public    Image LoadImage (strint s)  throws Eofexception, Malformedurlexception    {    ...    }    }

However, we do not need to advertise internal Java errors, nor should we advertise exceptions derived from RuntimeException.

Good exception handling

Good exception handling provides a unified mechanism for handling program errors. In fact, the Java language significantly improves the exception handling capability in software development by presenting the caller with an exception warning. 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, which illustrates the situation.

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

Public FileInputStream (String name) throws FileNotFoundException Java

Methods and constructors must declare the exceptions they might "throw" when they are called, and the keyword used is "throws". This exception hint in the method prototype increases the reliability of the program.

It is obvious that this approach prompts the caller of the method for possible exception conditions so that the caller can handle the exceptions appropriately. The following code shows how we captured and handled the FileNotFoundException exception:

1234567891011    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, which are check exceptions, user-defined exceptions, and the new Java Logging API (Java Logging API) introduced in JDK 1.4. All subclasses of java.lang.Exception belong to a check exception. A check exception (checked exception) is an 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. Good Java programs stipulate that custom exceptions encapsulate, report, and handle their own unique situations. The latest Java Logging API (logging API) can centralize the logging of exceptions. Bad Java exception handling

The bad side includes two situations: abuse of non-checked exceptions (unchecked exceptions) and misuse of catchall constructors. Both of these methods complicate the problem.

There is a category of exceptions that belong to RuntimeException subclasses, which are not checked by the compiler. For example, NullPointerException and arraystoreexception are examples of this type of exception. Programmers can subclass RuntimeException to circumvent the limitations of checking exceptions, making it easier for the methods that produce these exceptions to be used by their callers.

Professional development teams should only be allowed to do so in very few cases.

The second bad habit of exception handling is the Catchall constructor. The so-called "Catchall constructor" is an exception-capturing code module that can handle all the possible exceptions thrown at it.

The following is an example of a catchall processor:

    123456789    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 general procedure, but this type of constructor must be avoided when writing critical programs, unless they are authorized to federate with the central error processor.

In addition, the Catchall constructor is just a mechanism to speed up the programming process by avoiding error handling.

One disadvantage of exception handling is that it is difficult to adopt a good error handling strategy. Exceptions such as low-volume memory state recovery, write errors, and algorithmic errors are not easily resolved. You can try out the usual techniques such as looping, garbage collection, and reminding users to cope with the above situation.

Harsh treatment methods

Like many Java features and their APIs, Java's exception handling mechanism also has the "Overlord-bow" category of funny errors. For example, in order to throw out an exception, we do not hesitate to use the "new" keyword to allocate memory for it is such a case.

I do not know how many times I have made such a mistake in the face of serious compiler repeatedly. In this case, we are actually serving the language rather than making the language work for us. And the outofmemoryerrors we meet is the flaw in exception handling. This process is:

Use the finally module to close the file, resolve the exception to get the method and line of code where the problem occurred. The biggest flaw in this process is the need to capture OutOfMemoryError, which is not an anomaly to check! If you think about it, memory exhaustion is a fairly common situation. Any program that is closely related to the state of memory usage should capture and handle this error.

Some suggestions for using exceptions

1. The design of exception control is not intended to replace some simple tests. Use exceptions only in exceptional cases!

2. Do not refine the exception excessively. Instead of adding exception handling on each statement, it's a good idea to put the entire task inside a try block. If one of the operations fails, you can discard the task immediately.

3. Do not "suppress" the exception. For methods that need to advertise the exception, we can use the snapping method to force the exception to be closed, and if there is an exception, the exception will be "silently" ignored. If you feel that the anomalies will be very important, you must take more effort to control them properly.

4. Don't mind the abnormal delivery. If the calling method produces an exception, such as the ReadLine method, they are inherently able to catch the exceptions they might produce, in which case it is better to pass these exceptions instead of capturing them yourself.

The pros and cons of Java exception handling

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.