Exceptions in Java

Source: Internet
Author: User

Abnormal scenario Analysis:

L Programming Errors cause exceptions (Exception due programming errors): In this scenario, the exception is often in a programming error (e.g. NullPointerException or illegalargumentexception), Once the exception is thrown, the client becomes powerless.

The client code error caused the exception (Exception due client, code errors): The white point is the client attempting to invoke an operation that the API does not allow.

The resource failure resulted in an exception (Exception due to resource failures): An exception occurred due to insufficient memory or network connection failure. The presence of these exceptions the client can take appropriate action to restore the application to continue running.

Two types of exceptions are defined in Java:

L Checked Exception: This type of anomaly is a subclass of exception

L Unchecked exception: Such exceptions are subclasses of RuntimeException, although RuntimeException is also a subclass of exception, but they are special, they cannot pass the client Code to try to solve, so called unchecked exception

For example, the inheritance relationship for NullPointerException:

In the figure, NullPointerException inherits from RuntimeException, so it is unchecked exception.

Java is the first mainstream OO language with checked exception, and C + + and C # are not checked exception at all, and all of their exceptions are unchecked.

Best practices for several design anomalies:

1. When deciding whether to use checked exception or unchecked exception, ask yourself a question, "What kind of remedy will the client do if this exception is thrown?" "
If the client can recover the exception by other means, then this exception is checked exception; If the client is powerless to do so, the exception is unchecked exception; When the exception appears to do something to try to restore its action and not just print its information, in general, look at the following table:

Client ' s reaction when exception happens
Exception type

Client code cannot do anything
Make it an unchecked exception

Client code would take some useful recovery action based on information in exception
Make it a checked exception


In addition, try to use unchecked exception to handle programming errors: Because unchecked exception does not have to make the client code appear to handle them, they will suspend the program and print out the exception information where they appear. The Java API provides rich unchecked excetpion, such as NullPointerException, IllegalArgumentException and IllegalStateException, So I generally use these standard exception classes rather than creating new exception classes myself, so that my code is easy to understand and avoids consuming too much memory.

2. Protection of Encapsulation (Preserve encapsulation)

Don't let your checked exception upgrade to a higher level. For example, don't let SqlException extend to the business layer. The business layer does not need (don't care?) ) SQLException. You have two ways to solve this problem:

L Convert SqlException to another checked exception, if the client does not need to restore such an exception;

L transform SqlException into a unchecked exception if the client is powerless to do so;

In most cases, the client code is powerless against SqlException, so you don't hesitate to turn it into a unchecked exception, and look at the code below:
public void Dataaccesscode () {
try{
.. Some code that throws SQLException
}catch (SQLException ex) {
Ex.printstacktrace ();
}
}


It is understandable that the upper catch block prints the exception information tightly without any direct manipulation, because what else do you expect the client to do with SqlException? (but obviously this is not advisable as if nothing happened) so is there another way to be more feasible?

public void Dataaccesscode () {
try{
.. Some code that throws SQLException
}catch (SQLException ex) {
throw new RuntimeException (ex);
}
}

The above approach is to convert SqlException to RuntimeException, and once SqlException is thrown, the program throws RuntimeException, and the program is suspended and the client exception information is returned.

If you have enough confidence to restore it when SqlException is thrown, then you can also convert it to a meaningful checked exception, but I find it is enough to throw runtimeexception most of the time.

3. Do not create meaningless exceptions (Try not to create new custom exceptions if they does not has useful information for client code.)

See what's wrong with the code below?

public class Duplicateusernameexception
Extends Exception {}


It does not have any useful information other than a "meaning-clear" name. Don't forget exception with the others.like Java classes, clients can invoke methods in them to get more information.

We can add some of the necessary methods to it, as follows:

public class Duplicateusernameexception
Extends Exception {
Public duplicateusernameexception
(String username) {....}
Public String Requestedusername () {...}
Public string[] Availablenames () {...}
}



There are two useful methods in the new code: Reqeuestedusername (), the customer can get the requested name through it, Availablenames (), which the client can use to get a useful set of usernames. The client then obtains the information it returns to clarify the cause of its own operation failure. But if you do not want to add more information, then you can throw a standard exception:

throw new Exception ("Username already Taken");
Even worse, if you think that the client does not want to use too much action and just want to see the exception information, you can throw a unchecked exception:

throw new RuntimeException ("Username already Taken");

Alternatively, you can provide a way to verify that the username is occupied.

It is necessary to reiterate that checked exception should allow the client to get rich information from it. To make your code easier to read, be inclined to use unchecked excetpion to handle errors in the program (Prefer unchecked exceptions for all programmatic errors).

4. Document exceptions.

You can use the Javadoc ' s @throws tag to illustrate (document) that you want to throw checked exception or unchecked exception in your API. However, I prefer to use unit tests to illustrate (document) exceptions. Whichever way you use it, you have to let the client code know what exceptions you want to throw in your API. Here is an example of using unit tests to test indexoutofboundsexception:

public void Testindexoutofboundsexception () {
ArrayList blanklist = new ArrayList ();
try {
Blanklist.get (10);
Fail ("Should raise an indexoutofboundsexception");
} catch (Indexoutofboundsexception success) {}
}



The upper code will throw a indexoutofboundsexception when requested Blanklist.get (10), if not thrown, will fail ("should raise an indexoutofboundsexception ") indicates that the test failed. By writing test unit tests for anomalies, you can see not only how the exception works, but also how you can make your code more robust.

Best practices for using exceptions:

1. Always have to do some cleanup work.

2. Do not use exceptions to control processes (never using exceptions for flow control)

3. Do not ignore exceptions

4. Do not capture top-level exception

Reference documents:

http://blog.csdn.net/gotohbu/article/details/4332016

Exceptions in Java

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.