Exception cannot be used for logic processing

Source: Internet
Author: User
Exception cannot be used for logic processing

Exception is error processing, but cannot be used for logic processing. Suppose we encapsulate a msgqueue. This class is responsible for collecting client messages from one receiving thread on the server side, and the other working thread is responsible for extracting messages, and process the message.

 
ClassMSG {...};
ClassMsgqueue {
Public:
VoidPut (MSG)Throw(STD: length_error );
MSGGet()Throw(STD: out_of_range );
.....
}

Here we define two methods of msgqueue: collecting client messages, then saving the PUT Method of messages, as well as the get method for processing client messages and retrieving customer messages.

For the put method, due to limited memory, we cannot allow this msgqueue to save messages without limits. Therefore, when too many messages are saved and client messages cannot be saved, an STD: length_error exception is thrown.

For the get method, if there are no elements in the queue, we will tell the caller that the queue is empty, but an empty element cannot be returned here. Therefore, we will throw a STD :: out_of_range (when the queue of STL is empty, the Front () method can be called to retrieve elements without throwing any exception ).

Worker threadCodeAs follows:

 
MSG;
While(True){
Try{
MSG = msgqueue.Get();//Retrieve client messages
Handle (MSG );//Process client messages
}Catch(STD: out_of_range ){
Sleep (1);
}
}

Msgqueue is shared by the worker thread and the worker thread. The worker thread continuously polls and tries to determine whether the message can be retrieved. It cannot indicate that there is no new message. Wait for one second, you can retrieve the message and process it.

The problem with this Code is that the exception is used for logic processing and the msgqueue is empty. This is a normal scenario, because it is impossible to have a message at every moment. Exceptions are used for error processing, therefore, we should first determine whether msgqueue is empty or not before calling msgqueue. get () to retrieve the message.

ClassMsgqueue {
Public:
BoolIsempty ();
VoidPut (MSG)Throw(STD: length_error );
MSGGet()Throw(STD: out_of_range );
.....
}

After adding a member function to determine whether the queue is empty, the code of the worker thread is modified as follows:

MSG;
While(True){
If(Msgqueue. isempty ()){
Sleep (1);
Continue;
}
MSG = msgqueue.Get();//Retrieve client messages
Handle (MSG );//Process client messages
}

In this way, the code is much more concise and clear, without the appearance of block code like try {} catch {}, especially when there are many layers, it is difficult to see the code clearly.

As a msgqueue, not only the caller's call scenarios should be considered, but methods such as isempty () should be provided to prevent the caller from capturing exceptions during logical processing, write some obscure code.

When local control can meet our business needs, do not use exception handling. Please use exception for error handling.

 

When to use try and catch

Which error handling methods are applicable to exceptions? Where do I need try {} catch {}? For example, network exceptions and file IO exceptions? These typical errors read server responses from a server, network interruption may occur. Such processing code is suitable for try {} catch.

 
Try{
Writerequesttoserver ();
Readresponsefromserver ();
}Catch(Networkerror ){
//Handle network errors. For example, if the browser says the server cannot be connected
}

For example, in the process of reading and writing files like file I/O, if it is really bad luck, we must also handle bad sectors on the hard disk, a robustProgramConsider any possible errors.

 
Try{
Writefiletodisk ();
}Catch(Io_error ){
//If it is an I/O bad track, the common solution is to prompt the user to say that the disk or partition is damaged.
}

These are error handling scenarios where an exception try {} catch {} is used. You can see the code in try {} at a glance, an error is an invalid scenario, but it cannot be completely avoided.

 

Summary

Try {} catch {} These error handling statements can be used less and used less. The Code becomes block-based and it is easy to make the code hard to read. If you use exceptions for logic processing, the probability of try {} catch {} appears in the Code is greatly increased, leading to poor code readability.

For example, when the if else code block has more than three layers

 
If(...){
If(...){
If(....){
If(...){
....
}
}
}
}

This code is poorly read (no else is added, otherwise it will be dizzy). If the level of if exceeds three layers, I think the code should be restructured, because I think it will take at least an hour for developers to look at the code and reorganize the logic after a week. If you refactor the code, you only need ten minutes to understand the code logic)

When try {} catch {} is used, the layers of the code block will increase, and the code readability will deteriorate. It is accepted that it is used for error processing. If it is used for logic processing, there is no need for trouble. Please try to avoid it.

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.