Abnormal handling of "turn" programming idea

Source: Internet
Author: User

What do you mean, exception handling?

What is an exception (Exception)? As the name implies is an informal situation, there are undesirable accidents, exception handling is encountered in this contingency prepared for the countermeasures and solutions. For example, you drive a Rolls Royce on the road, suddenly a child appears in front of you, fortunately you sighted emergency brakes, and avoid a traffic accident. In this case, the sudden appearance of the child is abnormal, emergency braking is abnormal handling (in the face of this unexpected situation to take a solution).

The procedure comes from the reality, is the reality abstraction and the simulation, also will have the anomaly, therefore the unusual processing appears extremely important. Imagine if one of your phone's apps crashes in two, or all sorts of unexpected situations, you don't have the urge to throw your phone, will you use it again?

Solution for exception handling

Exception handling in C + +:

Exception handling in C + + is mainly implemented in two ways: (1). Returns the error code, (2) The Try...catch mechanism catches the exception.

Return error code

The return error code is the way the traditional C language handles exceptions. In a function, if an error or exception occurs that does not occur, an error code is returned directly, and the caller of the function processes the corresponding type of the error code that is returned when the function is called. Because of the historical reasons for C + + (developed by C), in order to be compatible, today's C + + programs can still see a lot of error code in the way up to throw exception information.

This approach is generally used for high performance requirements, commonly used in system libraries and interface implementations. So this approach allows for precise control of logic and allows programmers to focus only on logic and performance, while the integrity and robustness of the program is given to the upper-level caller for processing. It is implemented in the following ways:

example "1" divides two floating-point numbers and throws an error code if the divisor is 0 .

1. Define error code RetCode.h

1 #ifndef Retcode_h2 #defineRetcode_h3 4typedefLongReturnCode;5 6 //Success7 #defineRT_OK 0L8 //failed9 #defineRt_failed 1LTen  One //parameter Error A #defineRt_param_error 2L - //Unpredictable Errors - #defineRt_unexpected_error 3L the //NULL pointer - #defineRt_null_ptr 4L - //Allocating memory Errors - #defineRt_allocate_memory_failed 5L + //Operations not supported - #defineRt_unsupport_operate 6L +  A  at #endif/* Retcode_h */

How the error code is implemented :

1#include"RetCode.h"2#include <iostream>3 4 //determine if a floating-point number is 05 #defineDequalzeor (x) ((x) <= 0.0001 && (x) >-0.0001)6 7 //Division Operation8ReturnCode Division (DoubleDividend,DoubleDivisorDouble&result)9 {Ten     if(Dequalzeor (divisor)) One         returnRt_param_error; A     Else -     { -result = dividend/Divisor; the         returnRt_ok; -     } - } -  + intMainintargcChar**argv) - { +     DoubleR =0; AReturnCode ret = Division (5,0, R); at     if(Rt_param_error = =ret) -     { -Std::cout <<"parameter error, check if the divisor is 0. "<<Std::endl; -}Else -     { -Std::cout << R <<Std::endl; in     } -     return 0; to}

Try...catch mechanism catches exceptions

The above method of returning the error code may effectively define and control various errors and exceptions, but each call must check the error value, it is extremely inconvenient, and it is easy to double the program size. In fact, C + + has a special mechanism for handling exceptions, which is the try...catch mechanism.

Try {        //  throws an exception, or may throw an exception to the call catch  (Exceptioinobject        e) {// Handling Exceptions Catch  (...) {        //  Catch all types of exceptions }

Description

Code blocks in 1.try are used to throw (throw) exceptions, or to invoke functions, objects that may throw exceptions;

2.The Throw keyword can be used to throw an object of any type , either as an object of a class, as an object of a built-in data type (often called a variable), or as a pointer (the pointer itself is an object, a special object that points to the address of another object);

3. The e in the first catch bracket indicates the exception object, which can also be any type of object. When the throw-out object type is the same as the type of E, the exception is caught and the exception is handled in the catch code block.

4. The "..." in the second catch bracket indicates any type and can catch any type of exception.

5. A try can correspond to one or more catch,catch clauses that are checked in the same order that they were ordered after the try block, and once a match is found, subsequent catch clauses are no longer checked, by this rule, catch_all (catch (...). {}) represents exceptions that are handled in addition to the various exceptions listed earlier.

The 6.catch clause can contain a return statement, or it may not contain a return statement. Contains the return statement, the entire calling function ends, and the subsequent statement is no longer executed. Without a return statement, the next statement after the catch list is executed.

exception handling, separating normal logic from error handling, throwing exceptions by the implementation side of the function, catching the exception by the caller, and the caller knowing that the program function call is wrong and processing it, and whether or not to terminate the program is in the caller's hand.

We will use the above example with Try...catch ... Way to achieve

Example "2" divides two floating-point numbers and throws an exception if the divisor is 0 .

1#include <iostream>2 //determine if a floating-point number is 03 #defineDequalzeor (x) ((x) <= 0.0001 && (x) >-0.0001)4 5 using namespacestd;6 7 //Divisor is not a 0 exception8 classdivisorzeorexception{9  Public:TenDivisorzeorexception (Doublevalue): M_value (value) {} One  A     voidShowinfo () -     { -cout <<"The divisor"<< m_value <<"is wrong."<<Endl; the     } - Private: -     Doublem_value; - }; +  - DoubleDivision (DoubleDividend,Doubledivisor) + { A     if(Dequalzeor (divisor)) at     { -         Throwdivisorzeorexception (divisor); -     } -     returnDividend/Divisor; - } -  in intMain () - { to     Try +     { -         Doubleresult = Division (Ten,0); thecout <<"Result:"<< result <<Endl; *}Catch(divisorzeorexception e) $     {Panax Notoginseng e.showinfo (); -}Catch(...) the     { +cout <<"All exception"<<Endl; A     } the     return 0; +}

Advanced Features of exceptions

(1) Exception specification

You can list the exceptions that can be thrown with throw after the function, and ensure that the function does not throw any other type of exception. As the division function above changes to:

Double division (doubledoublethrow(divisorzeorexception) {      If  (Dequalzeor (divisor))    {        throw  divisorzeorexception (divisor);    }     return dividend/ divisor;}

If at run time, the function throws an exception that is not listed in its exception specification (and the exception thrown in the function is not processed inside the function), the system calls the function unexpected () defined in the C + + standard library. If the exception specification form is throw (), it means that no exception should be thrown.

(2) Inheritance of exception classes

Exception classes can also inherit, in the order in which the catch catches the exception, by subclasses to the parent class, so that the catch clauses are checked in the same order as they were ordered after the try block, so the most specific in the CATCH clause list (the most restrictive match condition, That is, a subclass) a catch clause must first appear . Suppose there are three exception classes, Exceptionc is a subclass of Exceptionb, Exceptionb is a subclass of Exceptiona, Try...catch ... is written as:

Try {    // The statement that could throw an exception }catch  (Exceptionc c    ) {// Handling Exceptionc Exceptions }catch  (exceptionb b) {    // handle EXCEPTIONB exception } Catch (Exceptiona a) {    // handle Exceptiona exception }

Exception classes in the C + + standard

A common set of exception classes has been defined in the C + + standard, with the following hierarchical relationships:

Exception is the parent of all exception classes, defining only the copy constructor, copy assignment operator, a virtual destructor, and a virtual member named what, and what function returns a const char* for returning some exception information.

Although there are not many classes defined in the C + + standard, we should try to make use of existing exception classes when defining our own exception classes, or at least inherit from the exception class to maintain the unity of the structure.

Turn from Luoweifu "abnormal handling of programming thought"

Abnormal handling of "turn" programming idea

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.