C + + Primer Learning note _88_ Tools for large programs-exception handling [Cont. 1]

Source: Internet
Author: User

Tools for large programs--Exception Handling[continued1]



Four, once again thrown

It is possible that a single Catchcannot handle an exception completely. After some corrective actions have been made,Catch It is possible to determine that the exception must be handled by a higher-level function in the function call chain .CatchThe ability to throw an exception to a higher function in the function call chain can be thrown again. Another throw is one that is not followed by a type or expressionThrow:

        Throw

EmptyThrowstatement will throw the exception object again, it can only present Catchor fromCatch called in the function . Assuming that the process code is inactive when it encounters an empty Throw, you callTerminate function .

Although another throw does not specify its own exception, it still passes an exception object along the chain, and the exception thrown is The original exception object , not CatchThe form of participation . WhenCatchwhen the form is a base class type ,we don't know the actual type thrown by another throw of an expression ,the type depends on the dynamic type of the exception object,and notCatchthe static type of the form participation. Like,from the band base class typeCatchanother throw of,an object of a derived type may actually be thrown.

Generally speaking, Catch able to change its shape and participation. After changing its shape, assuming that the catch throws an exception again, the change is propagated only when the exception specifier is a reference .

    catch (My_error &eobj)    {        eobj.status = Severeerr;        throw;//propagation Change    }    catch (Other_error eObj)    {        e.status = Baderr;        throw;//is just a copy of the object    }

V. Capturing all exception handling code

ability to use catch all exceptions Catch clause to handle exceptions that do not know the exact type. Catch clauses that catch all exceptions are in the form of (...) , such as:

    catch (...)    {        //...    }

Captures all exceptions. Catch clause matches a random type of exception.

catch (...) often used in conjunction with another thrown expression, Catch complete the partial work that can be done, and then throw the exception again:

void Manip () {    try    {        //...    }    catch (...)    {        //...        throw;    }}

Annotations

Assumptions catch (...) with other Catch clause, it must be the last , or whatever follows the Catch clauses will not be matched.



function test block and structure function

The constructor initialization is handled before entering the body of the constructor function, and the catch clause inside the constructor function body cannot handle exceptions that may occur when the constructor initialization is handled .

to handle exceptions from the constructor initializer , constructors must be written as functions Try block. the ability to use a function test block to associate a set of catch clauses with a function as a whole.

Template <class t> handle<t>::handle (T *p) Try:    ptr (P), use (New size_t (1)) {    //empty function Body} catch (const Std::bad_alloc &e) {    handle_out_of_memory (e);}

/span> Note: keywords try out of the current member initialization list , and the compound statement of the test block surrounds the function body of the constructor. catch member initialization list The exception thrown in is also capable of handling exceptions thrown from constructor function Body !

So: The constructor is going to handle an exception from the constructor initializer, the only way is to write the constructor as a function test block!


P587 Exercise 17.5//(a) class Exceptiontype {};throw new Exceptiontype (); catch (Exceptiontype *pet) {    //...}

(b) throw 8;catch (...) {    //...}

(c) enum Matherr {overflow,underflow,zerodivide};throw overflow;catch (matherr &ref) {    //...}

(d) typedef int Exceptype;throw 250;catch (exceptype) {    //...}


Vii. level of Exception class
The only action defined by the exception type is a virtual member named what, which returns the const char * object, which generally returns information used to construct the exception object at the thrown position. Because what is a virtual function, assuming that a reference to a base class type is captured, the call to what function executes the version number of the dynamic type that is appropriate for the exception object.


1. Exception Classes for bookstore applications
Applications often extend the exception hierarchy by deriving additional types from exception classes or intermediate base classes. These newly derived classes can represent exception types that are specific to the application realm.



Standard Exception class hierarchy


We are able to define our own level of exception to represent application-specific issues that may arise.

Class Out_of_stock:public Std::runtime_error{public:    explicit Out_of_stock (const std::string &s):        std:: Runtime_error (s) {}};class isbn_mismatch:public std::logic_error{public:    isbn_mismatch (const std::string &s ): Std::logic_error (s) {}    isbn_mismatch (const std::string &s,                  const std::string &lhs,const std:: String &rhs):        Std::logic_error (s), left        (LHS), right (RHS) {}    const std::string left,right;    Virtual ~isbn_mismatch () throw () {}};

By deriving from the standard exception class, you define application-specific exception types, and you can feel that the exception classes are organized hierarchically: as the layers deepen, each layer becomes a more special exception.

The first layer is the most general layer by Exception Class Representative , When this type of object is captured , all we know is that something went wrong .

The second layer will Exceptionspecial to two major categories:execution-time errors and logic errors. Our bookstore exception class represents events in a more specific layer . Out_of_stockclass represents an application-specific thing that might fail at execution time,the ability to use it to send signals that cannot fulfill an order. Isbn_mismatchexceptions are fromLogic_errormore special exceptions derived,In principle,programs can be called by theSAME_ISBNDetected a mismatch.ISBN.



2 , using the program APE-defined exception type

use your own exception classes in the same way that you use standard library classes .

Sales_item operator+ (const sales_item &lhs,const sales_item &rhs) {    if (!LHS.SAME_ISBN (RHS))    {        Throw Isbn_mismatch ("ISBN mismatch", Lhs.book (), Rhs.book ());    }    Sales_item ret (LHS);    RET + = RHS;    return ret;}

Then, the code using the plus operator can detect the error and write the appropriate error message:

    Sales_item item1,item2,sum;    while (Cin >> item1 >> item2)    {        try        {            sum = item1 + item2;        }        catch (const Isbn_mismatch &e)        {            cerr << e.what () << ": Left ISBN (" << e.left                 << "), right ISBN (" << e.right << ")"                 << Endl;        }    }

C + + Primer Learning note _88_ Tools for large programs-exception handling [Cont. 1]

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.