13 Programming Language Concepts Using C and C++_Exception Handling in C++ - Wikibooks, open books for an open world

Embed Size (px)

Citation preview

  • 8/10/2019 13 Programming Language Concepts Using C and C++_Exception Handling in C++ - Wikibooks, open books for

    1/19

    Programming Language Concepts Using C and

    C++/Exception Handling in C++

    Similar to Java, exceptions in C++ are most oftennot always!objects of a class type. That is, instead of

    returning a value of a certain type an exception object may be returned from the function. However, one canalso throw an exception object of a primitive type. The following is an example to this unlikely case.

    Example: Throwing an exception of a non-object type.

    enum ERESULT { arg_neg = - 1, ar g_t oobi g = - 2};

    l ong f act ( short n) { i f ( n MAX_ARG) throw ar g_t oobi g;

    i f ( n == 0 | | n == 1) return 1; el se return ( n * f act ( n 1) ) ;} / / end of l ong f act( shor t )

    Other peculiarities of exceptions in C++ are related to the way they are specified and handled. In addition to

    listing the exact list of exceptions thrown from a function by means of an exception specification, one can

    optionally remove the specification and get the liberty of throwing any exception.

    Example: Exception specifications.

    / / f 1 can t hr ow except i ons of t ypes E1 and E2voi d f 1( . . . ) throw( E1, E2) ;/ / f 2 does not t hr ow any except i ons at al lvoi d f 2( . . . ) throw( ) ;/ / f 3 can t hr ow except i ons of any type. Thi s mi ght be a good choi cedur i ng t he i ni t i al phases of a pr oj ect .voi d f 3( . . . ) ;

    If we explicitly list the exceptions thrown from a function and it turns out that an unexpectedexceptionthat is, an exception that is not listed in the specificationis thrown and not handled in the

    function call chain, a call to unexpect ed( ) , defined in the C++ standard library, is made. In other words,detection of specification violations is carried out at run-time. If the control flow never reaches the point

    where the unexpected exception is thrown, program will run without a problem.

    In line with its design philosophy C++ does not mandate that statements with a potential of throwing an

    exception be issued inside a t r yblock. Similar to Java exceptions deriving from Runt i meExcept i on,C++ exceptions need not be guarded. In case we may be able to figure out that the exception never arises

    we can remove the t r y- cat chkeywords and get cleaner code.

    Example: No mandatory try-catch blocks.

    Rat i onal di vi de_by_f i ve( doubl e x) { Rat i onal r at 1 = Rat i onal ( x) ;

    gramming Language Concepts Using C and C++/Exception Handling ... http://en.wikibooks.org/wiki/Programming_Language_Concepts_Using...

    19 20-11-2014 13:07

  • 8/10/2019 13 Programming Language Concepts Using C and C++_Exception Handling in C++ - Wikibooks, open books for

    2/19

    Rat i onal nonzer o_r at = Rat i onal ( 5) ; Rat i onal r et _rat = rat1. di vi de( nonzer o_r at ) ;

    return ret_rat ;} / / end of Rat i onal di vi de_by_f i ve( doubl e)

    Contents

    1 Exception Class

    2 Module

    2.1 Interface

    2.2 Implementation

    2.3 Test Program

    3 Input-Output in C++

    3.1 The Base Stream Class: ios

    3.2 Input Streams3.3 Output Streams

    3.4 File Input and Output

    4 Notes

    Exception Class

    Queue_Exceptions

    #i f ndef QUEUE_EXCEPTI ONS_HXX1.

    #def i ne QUEUE_EXCEPTI ONS_HXX2.

    3.

    #i ncl ude 4.

    usi ng namespace st d;

    5.

    6.

    namespace CSE224 {7.

    namespace DS {8.

    namespace Excepti ons {9.

    Note our exception class does not have any member fields. In other words, we have no means to identify

    details of the situation. All we know is we have a problem, nothing more! Although in our case we do not

    gramming Language Concepts Using C and C++/Exception Handling ... http://en.wikibooks.org/wiki/Programming_Language_Concepts_Using...

    19 20-11-2014 13:07

  • 8/10/2019 13 Programming Language Concepts Using C and C++_Exception Handling in C++ - Wikibooks, open books for

    3/19

    need any details about the nature of the problem, this is not always the case.

    Take the factorial example for instance. We may want to pass the value of the argument that gave rise to the

    exceptional condition. This is equivalent to saying that we want to tell the difference between exception

    objects of the same class. As a matter of fact, we may formulate the problem as that of differentiating

    between objects of the same class, be that an exception object class or any other. We can do this simply by

    adding fields to the class definition.

    Fact_Exceptions

    cl ass Negat i ve_Ar g {publ i c: voi d error ( voi d) { cerr

  • 8/10/2019 13 Programming Language Concepts Using C and C++_Exception Handling in C++ - Wikibooks, open books for

    4/19

  • 8/10/2019 13 Programming Language Concepts Using C and C++_Exception Handling in C++ - Wikibooks, open books for

    5/19

    What follows is a forward class declaration. Its purpose is similar to that of forward declaration ala C: we

    declare our intention of using a class named Queue_Nodeand defer its definition to some other place.

    Note we cannot declare an object of this type. This is due to the fact that C++ does not let you declare

    variables to be of types whose definitions are not completed. Because compiler cannot figure out the amount

    of memory required for the object. However, we can declare variables to be pointers or referencesread it

    as "constant pointers"to such a class.

    c l ass Queue_ Node;12.

    c l ass Queue {13.

    In some cases, it is convenient to allow a certain function/class to access the non-public members of a classwithout allowing access to the other functions/classes in the program. Thefriend mechanismin C++ allows a

    class to grant functions/classes free access to its non-publ i cmembers.

    A friend declaration begins with the keyword f r i end. It may appear only within a class definition. In otherwords, it is the class that declares a function/class to be its friend, not the other way around. That is, you

    cannot simply declare a class as your friend and access its fields.

    Since friends are not members of the class granting friendship, they are not affected by the publ i c,pr ot ect ed, or pr i vat esection in which they are declared within the class body. That is, frienddeclarations may appear anywhere in the class definition.

    According to the following declaration, overloaded shift operator (

  • 8/10/2019 13 Programming Language Concepts Using C and C++_Exception Handling in C++ - Wikibooks, open books for

    6/19

    providing a friend declaration such as the following.

    f r i end ostr eam& operat or

  • 8/10/2019 13 Programming Language Concepts Using C and C++_Exception Handling in C++ - Wikibooks, open books for

    7/19

    Note all fields of the following class definition are pr i vat e. There are no functions to manipulate theobjects, either. So, it looks like we need some magic for creating and manipulating an object of the class.

    Answer lies in Queue_Nodes relation to Queue: Queue_Nodeis tightly coupled to Queue. AQueue_Nodeobject can exist only within the context of a Queueobject. This fact is reflected in the frienddeclaration. Thanks to this declaration, we can [indirectly] manipulate a Queue_Nodeobject throughoperations on some Queueobject.

    c l ass Queue_ Node {30.

    f r i end c l ass Queue;31.

    Next statement declares the shift operator to be a friend to the Queue_Nodeclass. A similar declaration

    had been made in the Queueclass, which means that one single function will have the privilege of peekinginto the innards of two different classes.

    f r i end ostr eam& operat or

  • 8/10/2019 13 Programming Language Concepts Using C and C++_Exception Handling in C++ - Wikibooks, open books for

    8/19

    #i ncl ude

    #i ncl ude 2.

    usi ng namespace st d;3.

    4.

    #i ncl ude " ds/ Queue"

    5.

    #i ncl ude " ds/ except i ons/ Queue_Excepti ons"6.

    usi ng namespace CSE224: : DS: : Except i ons;7.

    8.

    namespace CSE224 {9.

    namespace DS {10.

    Queue: :11.

    Queue( const Queue& r hs) : _ f ront ( NULL) , _ rear ( NULL) , _ s i z e( 0) {12.

    Queue_Node *p t r = rhs . _ f ront ;13.

    f or ( unsi gned i nt i = 0; i i nsert ( pt r - >_ i t em) ;15.

    pt r = pt r - >_next ;16.

    } / / end of f or ( unsi gned i nt i = 0; i < r hs. _s i ze; i ++)17.

    } / / end of copy const r uct or18.

    Our destructor, implicitly invoked by the programmer (through del et ein deallocating heap objects) or by

    the compiler-synthesized code (in the process of deallocating static and run-time stack objects), deletes allnodes in the queue and then proceeds with cleaning the room reserved for the fields. Had we forgotten to

    remove the items we would have ended up with the picture given below, which is actually the same picture

    we would have got without the destructor.

    gramming Language Concepts Using C and C++/Exception Handling ... http://en.wikibooks.org/wiki/Programming_Language_Concepts_Using...

    19 20-11-2014 13:07

  • 8/10/2019 13 Programming Language Concepts Using C and C++_Exception Handling in C++ - Wikibooks, open books for

    9/19

    Note the shaded region denotes the memory returned to the allocator by the del et eoperator itself, not the

    destructor.[3]All queue nodes reachable only through the fields in the shaded region have now become

    garbage. So, we must remove all queue items when the queue is deleted, which is what we do in thedestructor body.

    Note also we do not write the code within a t r y- cat chblock. Unlike Java, thats OK with C++; you canchoose to omit the t r y- cat chblock if you think they will never happen. In this case, the number ofremovals is guaranteed to be as many as the number of items in the queue and this cannot give rise to any

    exceptional condition.

    Queue: :20.

    ~Queue( voi d) {21.

    unsi gned i nt s i ze = _ s i ze;22.

    f or ( unsi gned i nt i = 0; i 0; i - - ) r emove( ) ;30.

    31.

    Queue_Node *p t r = rhs . _ f ront ;32.

    gramming Language Concepts Using C and C++/Exception Handling ... http://en.wikibooks.org/wiki/Programming_Language_Concepts_Using...

    19 20-11-2014 13:07

  • 8/10/2019 13 Programming Language Concepts Using C and C++_Exception Handling in C++ - Wikibooks, open books for

    10/19

    f or ( unsi gned i nt i = 0; i i nsert ( pt r - >_ i t em) ;34.

    pt r = pt r - >_next ;35.

    } / / end of f or ( unsi gned i nt i = 0; i < r hs. _s i ze; i ++)36.

    37.

    i f ( rhs . _s i ze == 0) {38.

    _ f r ont = _rear = NULL;39.

    _si ze = 0;40.

    re turn( *t hi s) ;41.

    } / / end of i f ( r hs. _s i ze == 0)

    42.

    43.

    re turn ( *t hi s) ;44.

    } / / end of assi gnment oper at or45.

    46.

    bool Queue: :47.

    operat or==( const Queue& r hs) {48.

    i f (_si ze ! = r hs . _ si z e) re turn f al se;49.

    i f (_si ze == 0 | | t hi s == &r hs) re turn t rue;50.

    51.

    Queue_Node *p t r = _ f r ont ;52.

    Queue_Node *ptr_rhs = rhs . _ f ront ;53.

    54.

    f or ( unsi gned i nt i = 0; i _i t em ! = ptr_ rhs- >_i t em) 56.

    re turn f a l s e;57.

    p t r = pt r - >_next ;

    58.

    ptr_rhs = ptr_rhs- >_next ;59.

    } / / end of f or( unsi gned i nt i = 0; i < _si ze; i ++)60.

    gramming Language Concepts Using C and C++/Exception Handling ... http://en.wikibooks.org/wiki/Programming_Language_Concepts_Using...

    f 19 20-11-2014 13:07

  • 8/10/2019 13 Programming Language Concepts Using C and C++_Exception Handling in C++ - Wikibooks, open books for

    11/19

    61.

    re turn t rue;62.

    } / / end of equal i t y- t est oper ator63.

    64.

    doubl e Queue: :65.

    peek( voi d) throw( Queue_ Empt y) {66.

    i f ( empt y( ) ) throw Queue_Empt y( ) ;67.

    68.

    re turn(_ f r ont - >_ i t em) ;69.

    } / / end of doubl e Queue: : peek( voi d)70.

    71.

    doubl e Queue: :72.

    r emove( voi d) throw( Queue_Empt y*) {73.

    i f ( empt y( ) ) throw new Queue_Empt y( ) ;74.

    75.

    doubl e re t_val = _f r ont - >_ i t em;76.

    Queue_Node *t emp_node = _ f ront ;77.

    78.

    i f (_ f r ont == _r ear ) _ f ront = _rear = NULL;79.

    el se _ f ront = _front - >_next ;80.

    81.

    del et e t emp_node;82.

    _si ze- - ;83.

    84.

    re turn r et _val ;85.

    } / / end of doubl e Queue: : r emove( voi d)86.

    87.

    88.

    gramming Language Concepts Using C and C++/Exception Handling ... http://en.wikibooks.org/wiki/Programming_Language_Concepts_Using...

    f 19 20-11-2014 13:07

  • 8/10/2019 13 Programming Language Concepts Using C and C++_Exception Handling in C++ - Wikibooks, open books for

    12/19

    voi d Queue: :

    i nsert ( doubl e val ue) {89.

    Queue_Node *new_node = new Queue_ Node( val ue) ;90.

    91.

    i f ( empt y( ) ) {

    92.

    _ f r ont = _rear = new_node;93.

    _si ze = 1;94.

    re turn;95.

    } / / end of i f ( empt y() )96.

    97.

    _r ear - >_next = new_node;98.

    _r ear = _r ear - >_next ;99.

    _si ze++;100.

    } / / end of voi d Queue: : i nser t ( doubl e)101.

    102.

    bool Queue: :103.

    empt y( voi d) { re turn (_si ze == 0) ; }104.

    The following output operator definition makes use of both the Queueand the Queue_Nodeclasses. It firstprints the length of the queue by using a private field of the Queueclass and then outputs the contents ofthe corresponding queue by traversing each and every node, which are of Queue_Nodetype. For this

    reason we had to make this function a friend to both classes.

    ostr eam& operat or

  • 8/10/2019 13 Programming Language Concepts Using C and C++_Exception Handling in C++ - Wikibooks, open books for

    13/19

    re turn( os) ;

    } / / end of i f ( r hs. _s i ze == 0)112.

    113.

    os

  • 8/10/2019 13 Programming Language Concepts Using C and C++_Exception Handling in C++ - Wikibooks, open books for

    14/19

    usi ng namespace CSE224: : DS: : Except i ons;9.

    10.

    i nt mai n( voi d) {11.

    Queue q1;12.

    st r i ng f name( " Queue_Test . i nput " ) ;13.

    i f s t r eam i nf i l e( f name. c_st r ( ) ) ;14.

    15.

    i f ( ! i nf i l e) {16.

    cout

  • 8/10/2019 13 Programming Language Concepts Using C and C++_Exception Handling in C++ - Wikibooks, open books for

    15/19

    i nf i l e. c l ose( ) ;29.

    30.

    cout

  • 8/10/2019 13 Programming Language Concepts Using C and C++_Exception Handling in C++ - Wikibooks, open books for

    16/19

    The attributes of a particular stream type is somehow mangled in its name. For example, i f st reamstandsfor a file stream that we us as a source of input. Similarly, ost r i ngst r eamis an in-memory bufferastring objectstream that is used as a sink of output.

    The Base Stream Class: ios

    Whatever the name of the class being used might be it eventually derives from i os, the base class of theiostream library. This class contains the functionality common to all streams, such as accessor-mutator

    functions for manipulating state and format. In the former group are included the following functions:

    i ost at e r dst at e( ) const : Returns the state of the current stream object, which can be anycombination of the following: good, eof, f ai l , and bad.voi d setstate( i ost at e new_st at e) :In addition to the already set flags, sets the state of thestream to new_st at e. Note this function cannot be used to unset the flag values.voi d cl ear ( i ost at e new_st at e = i os: : goodbi t ) : Sets the state to the value passed innew_st ate.i nt good( voi d) : Returns trueif the last operation on the stream was successful.i nt eof( voi d) : Returns trueif the last operation on the stream found the end of file.i nt f ai l ( voi d) : Returns trueif the last operation on the stream was not successful and no datawas lost due to the operation.

    i nt bad( voi d) : Returns trueif the last operation on the stream was not successful and data waslost as a result of the operation.

    For manipulating the format, we have

    char f i l l ( voi d) const : Returns the padding character currently in use. The default characteris space.

    char f i l l ( char new_pad_char) : Sets the padding character to new_pad_char and returnsthe previous value.i nt pr eci si on( voi d) const : Returns the number of significant digits to be used for output offloating point numbers. The default value is 6.

    i nt pr eci si on( i nt new_pre) : Sets precision to new_preand returns the previous value.i nt wi dt h( voi d) const : Returns the output field width. Default value is 0, which means asmany characters as necessary are used.

    i nt wi dt h( i nt new_wi dt h) : Sets width to new_wi dthand returns the previous value.f mt f l ags set f( f mt f l ags f l ag) : Sets one of the flags, which are used to control the wayoutput is produced. f l agcan have one of the following: (for base value used in output of integralvalues) i os: : dec, i os: : oct , i os: : hex, (for displaying floating point values)

    i os: : sci ent i f i c, i os: : f i xed, (for justifying text) i os: : l ef t , i os: : r i ght ,i os: : i nt er nal , (for displaying extra information) i os: : showbase, i os: : showpoi nt ,i os: : showpos, i os: : uppercase. As in the next four functions, this function returns the statethat was in effect prior to the call.

    gramming Language Concepts Using C and C++/Exception Handling ... http://en.wikibooks.org/wiki/Programming_Language_Concepts_Using...

    f 19 20-11-2014 13:07

  • 8/10/2019 13 Programming Language Concepts Using C and C++_Exception Handling in C++ - Wikibooks, open books for

    17/19

    f mt f l ags set f( f mt f l ags f l ag, f mt f l ags mask) : Clears the combination of flags passedin mask and then sets the flags passed in f l ag.f mt f l ags unset f( f mt f l ags f l ag) : Reverse of set f, this function makes sure thecombination of flags passed in f l agis not set.f mt f l ags f l ags( voi d) const : Returns the current format state.f mt f l ags f l ags( f mt f l ags new_f l ags) : Sets the format state to new_f l ags.

    Input Streams

    On top of the functionality listed in the previous section, all input streams in C++ provide support for the

    following functions.

    i str eam& oper at or>>( t ype dat a) : Overloaded versions of the shift-in (or extraction)operator are used to read in values of various types and can further be overloaded by the programmer.

    It can be used in a cascaded manner and in case the input operation is unsuccessful it returns f al se,which means it can also be used in the context of a boolean expression.

    i nt get ( voi d) : Returns the character under the read head and advances it by one.i nt peek( voi d) : Like the previous function, peekreturns the character under the read head but

    doesn't move it. That is, peekdoes not alter the stream contents.i str eam& get ( char & c) : Cascaded version of get ( voi d) , this function is equivalent tooperator>>( char &) . That is

    i n_st r . get ( c1) . get ( c2) . get ( c3) ; i n_st r >> c1 >> c2 >> c3;

    i str eam& get ( char * st r , st r eamsi ze l en, char del i m = ' \n' ) : Reads anul l -terminated string into st r . Length of this string depends on the second and third arguments,which hold the size of the buffer and the sentinel character, respectively. If l en - 1is scannedwithout reading the sentinel character, ' \0' is appended to the buffer and returned in the firstargument. If the sentinel character is reached before filling in the buffer, the read head is left on the

    sentinel character and all that has been read up to that point with the terminating ' \0' is returned inthe buffer.

    i str eam& get l i ne( ct ype* st r , st r eamsi ze l en, char del i m = ' \n' ) : Similar tothe previous function, get l i neis used to read a nul l -terminated string into its first argument.However, in case the sentinel character is reached before the buffer is filled, the sentinel character is

    not left in the stream but read and discarded. Note the type of the first argument is a pointer to one of

    char , unsi gned char , or si gned char .i str eam& r ead( voi d* buf , st r eamsi ze l en) : Reads l enbytes into buf, unless theinput ends first. If input ends before l enbytes are read this function sets the i os: : f ai l flag andreturns the incomplete result.

    i str eam& put back( char c) : Corresponding to unget c( char ) of C, this function attempts toback up one character and replace the character that has been backed up with c. Note this operation is

    guaranteed to work only once. Consecutive uses of it may or may not work.

    i str eam& unget ( voi d) : Attempts to back up one character.i str eam& i gnor e( st r eamsi ze l en, char del i m = t r ai t s: : eof) : This functionreads and discards as many as l encharacters or all characters up to and including the del i m.

    Output Streams

    Complementing the operations listed in the previous section are the operations applied on an output stream.

    Before we give a listing of these operations, we should mention one crucial point: in order for the outputoperations to take effect one of the following conditions must be met:

    An endl manipulator or ' \n' is inserted into the stream.1.A f l ushmanipulator is inserted into or a f l ush( ) message is sent to the stream.2.

    gramming Language Concepts Using C and C++/Exception Handling ... http://en.wikibooks.org/wiki/Programming_Language_Concepts_Using...

    f 19 20-11-2014 13:07

  • 8/10/2019 13 Programming Language Concepts Using C and C++_Exception Handling in C++ - Wikibooks, open books for

    18/19

    The buffer attached to the stream is full.3.

    An i str eamobject tied to the stream performs an input operation. Tying two streams means theiroperations will be synchronized. A popular example is the ci n-cout pair: before a message is sent toci ncout is flushed. That is,

    4.

    cout

  • 8/10/2019 13 Programming Language Concepts Using C and C++_Exception Handling in C++ - Wikibooks, open books for

    19/19

    the file] i os: : end.

    As a closing remark of this handout we should mention the possibility of simultaneously reading from and

    writing to the same file. In such a case, we can construct a fstreamobject and use it to achieve our goal.

    Notes

    Actually, there is a difference. Be that a plain object or an exception object, an object created in theheap is managed by the programmer and must be freed by her

    1.

    As a matter of fact, you can pass a pointer to some area in other parts of the address space such as

    the static data or run-time stack regions. But then how are you going to decide whether to free the

    region or not? If it points to some place in the heap, it is the programmers responsibility and she must

    free the object; if the pointed object is not in the heap its lifetime will be managed by the compiler.

    Wed better be more deterministic and create all such objects in the heap or have the handler accept

    an extra argument. Or yet better, choose to pass objects, not pointers to object.

    2.

    Observe this is basically the same region that would have been returned with f reein the case of amal l oced heap object: the region pointed to by the pointer. This semblance leads us to an informaldefinition: del et eoperator is implicit invocation of the destructor plus f ree.

    3.

    Retrieved from "http://en.wikibooks.org

    /w/index.php?title=Programming_Language_Concepts_Using_C_and_C%2B%2B

    /Exception_Handling_in_C%2B%2B&oldid=2718705"

    This page was last modified on 27 October 2014, at 21:14.

    Text is available under the Creative Commons Attribution-ShareAlike License.; additional terms may

    apply. By using this site, you agree to the Terms of Use and Privacy Policy.

    gramming Language Concepts Using C and C++/Exception Handling ... http://en.wikibooks.org/wiki/Programming_Language_Concepts_Using...