Exception Handling ()

Source: Internet
Author: User

Runtime exceptions:
A runtime exception is thrown if no declaration is required during method definition;
You do not need to capture this runtime exception when calling this method;
Runtime exception is derived from the java. lang. runtimeexception or java. lang. error class.

* Checked exceptions:
When defining a method, you must declare all possible checked exceptions;
When calling this method, you must capture its checked exception; otherwise, you must pass its exception;
Checked exception is derived from the java. lang. exception class.


"This is a good article on exception Processing. Starting from the introduction of java exception concepts, this article explains the exception type (checked/unchecked) in sequence, and the best implementation of exception Processing:

1. Several classic bases for selecting checked or unchecked

2. exception Encapsulation

3. Do not create your own exception unless necessary

4. Do not use exception for Process Control

5. Do not ignore caught exceptions easily.

6. Do not simply capture exceptions on the top layer"

-- Select from javadigest.net to introduce the original article

 

"The javadigest.net website does not know whether it is frequently used. Just like its name, it allows us to digest java more effectively, or it is like a transfer station, at least this is true for me. Some of the good ones can be said to be very classic technical articles. I obtained them for the first time. More often, I used javadigest.net to get lazy, if it is a classic article recently, there is a connection between the introduction text and the original text."

-- We are very honored to recommend javadigest.net to you in this episode.

 

 

 

One problem with exception handling is to understand when and how to use them. In this article, I will introduce some best practices for exception handling, and I will also involve the use of checked exception, which is highly controversial recently.

As developers, we all want to write code that solves the problem and is of high quality. Unfortunately, some side effects (side effects) are growing along with exceptions in our code. No effect, no one liked side effects, so we quickly avoided it in our own way. I have seen some smart programmers use the following methods to handle exceptions:

 

Public void consumeandforgetallexceptions (){
Try {
... Some code that throws exceptions
} Catch (exception ex ){
Ex. printstacktrace ();
}
}

 


Is there any problem with the above Code?

 

Before answering the questions, let's think about how the answer is correct? Yes, once the program encounters an exception, it should suspend the program and "do" something. Is the above code like this? Look, what does it hide? It swallowed all the "Bitter Water" in its stomach (printed exception information on the console), and then everything went on. On the surface, it looked like nothing happened ......, Obviously, the effects of the above Code are not what we expected.

 

What happened later?

 

Public void somemethod () throws exception {
}

 


What is the problem with the above Code?

 

Obviously, the method body above is empty, and it does not implement any function (no code). What exceptions does a blank method throw? Of course, java does not prevent you from doing this. Recently, I encountered a similar situation where the method declaration throws an exception, but there is no "opportunity" in the code to "display" the exception. When I asked the developer why he wanted to do this, he replied, "I know, it does, but I used to do this and it does work for me ."

 

The c ++ community has spent several years practicing how to use exceptions, and the debate on such issues has just begun in the java Community. I have seen many java programmers argue about exceptions. If an exception is improperly handled, the execution speed of the application can be greatly slowed down because it consumes memory and cpu to create, throw, and capture exceptions. If you rely too much on exception handling, the code will have an impact on both easy-to-read and easy-to-use aspects, so that we can write the above two "bad" codes.

 

Exception Principle

 

In general, there are three different "scenarios" that can cause exceptions to be thrown:

L exception due to programming errors (exception due programming errors): In this scenario, exceptions are often in programming errors (such as nullpointerexception or illegalargumentexception). Once an exception is thrown, the client becomes powerless.

L exception caused by client code error (exception due client code errors): The White point is the operation that the client attempts to call api is not allowed.

L exception due to resource failures: Exceptions may occur due to insufficient memory or network connection failure. When these exceptions occur, the client can take appropriate measures to resume the continued operation of the application.

 

Java exception type

Java defines two types of exceptions:

L checked exception: these exceptions are subclasses of exception.

L unchecked exception: these exceptions are subclasses of runtimeexception. Although runtimeexception is also a subclass of exception, they are special and cannot be solved through client code. Therefore, they are called unchecked exception.

For example, the nullpointerexception inheritance relationship is as follows:


Figure 1. sample exception hierarchy

 

In the figure, nullpointerexception is inherited from runtimeexception, so it is an unchecked exception.

 

In the past, I used to apply more checked exceptions than unchecked exceptions. Recently, the java Community stirred up a debate on the value of checked exceptions and their use. This debate originated from the fact that java is the first mainstream oo language with checked exception, and c ++ and c # both have no checked exception at all, and all their exceptions are unchecked.

 

A checked exception forces the client to throw and capture it. Once the client cannot effectively handle these thrown exceptions, it will impose an unexpected burden on program execution.

 

Checked exception may also cause encapsulation leakage. Check the following code:

 

Public list getallaccounts () throws
Filenotfoundexception, sqlexception {
...
}

 


The preceding method throws two exceptions. The client must capture and process these two exceptions, even if you do not know whether the exception is caused by file or database operations. Therefore, exception handling at this time will lead to an inappropriate coupling between a method and a call.

 

Next I will provide several best practices for design exceptions (best practises for designing the api)

 

1. When you want to decide whether to adopt checked exception or unchecked exception, you should ask yourself, "What kind of remedy will the client do if such exception is thrown ?"

[Original article: when deciding on checked exceptions vs. unchecked exceptions, ask yourself, "what action can the client code take when the exception occurs? "]

If the client can recover an exception through other methods, this exception is a checked exception. If the client is powerless for this exception, this exception is an unchecked exception. In terms of usage, when an exception occurs, do some actions to restore it instead of simply printing its information. In general, see the following table:

Client's reaction when exception happens
Exception type

Client code cannot do anything
Make it an unchecked exception

Client code will 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 need to be processed by the client code display, they will suspend the program and print the exception information at the place where it appears. Java APIs provide a variety of unchecked excetpion, such as nullpointerexception, illegalargumentexception, and illegalstateexception. Therefore, I generally use these standard exception classes instead of creating new ones, this makes my code easy to understand and avoids excessive memory consumption.

 

2. preserve encapsulation)

Do not upgrade the checked exception to a higher level. For example, do not extend sqlexception to the business layer. The business layer does not need (do not care ?) Sqlexception. You have two ways to solve this problem:

L change sqlexception to another checked exception, if the client does not need to recover this exception;

L change sqlexception to an unchecked exception, if the client cannot do anything about this exception;

In most cases, the client code is powerless to sqlexception, so you do not have to hesitate to convert it into an unchecked exception. Let's look at the following code:

 

Public void dataaccesscode (){
Try {
.. Some code that throws sqlexception
} Catch (sqlexception ex ){
Ex. printstacktrace ();
}
}


The catch Block above closely prints exception information without any direct operations. This is excitable, because what else do you expect the client to do for sqlexception? (But obviously, this is not desirable if nothing happens.) Is there another more feasible method?

 

Public void dataaccesscode (){
Try {
.. Some code that throws sqlexception
} Catch (sqlexception ex ){
Throw new runtimeexception (ex );
}
}

 


The above method is to convert sqlexception to runtimeexception. Once sqlexception is thrown, the program will throw a runtimeexception. In this case, the program is suspended and the client exception information is returned.

 

If you have enough confidence to restore it when sqlexception is thrown, you can also convert it into a meaningful checked exception, however, I found that runtimeexception is enough in most cases.

 

3. do not create meaningless exceptions (try not to create new custom privileges tions if they do not have useful information for client code .)

Let's take a look at the following code?

Public class duplicateusernameexception
Extends exception {}


It does not have any useful information except a "meaningful" name. Do not forget that exception is the same as other java classes. The client can call the methods to obtain more information.

We can add some necessary methods for 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 (), through which the customer can obtain the Request Name; availablenames (), through which the client can obtain a set of useful usernames. In this way, the client will obtain the returned information to identify the cause of its operation failure. However, if you do not want to add more information, you can throw a standard exception:

Throw new exception ("username already taken ");

 

In other cases, if you think that the client does not want to use too many operations but only want to see the exception information, you can throw an unchecked exception:

Throw new runtimeexception ("username already taken ");

 

In addition, you can provide a method to verify whether the username is occupied.

 

It is necessary to reiterate that the checked exception should allow the client to obtain rich information. To make your code more readable, you may prefer to use unchecked excetpion to handle errors in your program (prefer unchecked exceptions for all programmatic errors ).

 

4. document exceptions.

You can use the javadoc's @ throws tag to indicate that (document) Your api will throw a checked exception or unchecked exception. However, I prefer to use unit tests to explain (document) exceptions. No matter which method you use, you need to let the client code know the exception to be thrown in your api. Here is an example of indexoutofboundsexception testing:

Public void testindexoutofboundsexception (){
Arraylist blanklist = new arraylist ();
Try {
Blanklist. get (10 );
Fail ("shocould raise an indexoutofboundsexception ");
} Catch (indexoutofboundsexception success ){}
}

 

The above code will throw indexoutofboundsexception when requesting blamklist. get (10). If it is not thrown, the fail ("shocould raise an indexoutofboundsexception") is displayed, indicating that the test failed. By writing unit tests with test exceptions, you can not only see how exceptions work, but also make your code more and more robust.

 

 

The authors below will introduce best practices for using exceptions)
1. always do some cleanup (always clean up after yourself)

If you use resources such as database connections or network connections, remember to do some cleanup work (such as closing database connections or network connections). If your api throws an unchecked exception, then you need to try-finally for necessary cleanup:

Public void dataaccesscode (){
Connection conn = null;
Try {
Conn = getconnection ();
.. Some code that throws sqlexception
} Catch (sqlexception ex ){
Ex. printstacktrace ();
} Finally {
Dbutil. closeconnection (conn );
}
}

Class dbutil {
Public static void closeconnection
(Connection conn ){
Try {
Conn. close ();
} Catch (sqlexception ex ){
Logger. error ("cannot close connection ");
Throw new runtimeexception (ex );
}
}
}

 

Dbutil is a tool class to close connection. It is necessary to say that the importance of using finally is that it will be executed no matter whether the program encounters an exception or not. In the above example, the connection is closed in finally. If an error occurs when the connection is closed, a runtimeexception is thrown.

 

2. Do not use exceptions to control the process (never use exceptions for flow control)

In the following code, maximumcountreachedexception is used to control the process:

Public void useexceptionsforflowcontrol (){
Try {
While (true ){
Increasecount ();
}
} Catch (maximumcountreachedexception ex ){
}
// Continue execution
}

Public void increasecount ()
Throws maximumcountreachedexception {
If (count & amp; gt; = 5000)
Throw new maximumcountreachedexception ();
}

 

The preceding useexceptionsforflowcontrol () uses an infinite loop to increase the count until an exception is thrown. This method does not mean that the Code is not easy to read, but it reduces the execution efficiency of the program.

Remember to handle exceptions only when exceptions are to be thrown.

 

3. Do not ignore exceptions

If you do not want to recover an exception when it is thrown, you do not have to hesitate to convert it to unchecked exception, instead of using an empty catch Block or not doing anything to ignore it, it seems that nothing has happened on the surface.

 

4. Do not capture exceptions on the top layer

Unchecked exception is a subclass of runtimeexception, and runtimeexception inherits exception. Therefore, if the exception is captured, you also capture runtimeexception, as shown in the following code:

Try {
..
} Catch (exception ex ){
}


Once you write the above Code (note that the catch block is empty), it will ignore all exceptions, including unchecked exception.

 

5. log exceptions just once

Logging the same exception stack trace more than once can confuse the programmer examining the stack trace about the original source of exception. so just log it once.

 

Summary

Here are some best practices for exception handling. I don't want to start another round of debate on checked exception and unchecked exception. You can customize your own Exception Handling Based on your actual situation. I firmly believe that we will have a better way to handle exceptions in our code.

 

I would like to thank bruce eckel, joshua kerievsky, and somik raha for their support for writing this article.

This article is from "My Super invincible blog"

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.