CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 16
  1. #1
    Join Date
    Aug 2006
    Posts
    515

    Does error checking make code look ungly?

    I have to insert a lot of data points from a structure which looks like this:
    Code:
    boo result = false;
    
    result = InsertData( temperature);
    
    if (result == false)
    {
       AfxMessageBox("An error occured");
       return;
    }
    
    result = InsertData( pressure );
    
    if (result == false)
    {
       AfxMessageBox("An error occured");
       return;
    }
    
    result = InsertData( location );
    
    if (result == false)
    {
       AfxMessageBox("An error occured");
       return;
    }
    
    result = InsertData( .... );
    
    if (result == false)
    {
       AfxMessageBox("An error occured");
       return;
    }
    The InsertData() function above is pusdocode but the point is that this function (or the like) returns true or false. If a false occurs anywhere it is time to abort and quite the operation. In real situation I have a lot of these InsertData() function and I need to check the value after each one. It makes the code look a little ugly and error check code/user prompt message is repetitive. Is there a way to make it better? How about I put the error checking as #define ?
    Code:
    #define DO_ERROR_CHECK if (result == false) \
     { \
        AfxMessageBox("An error occured"); \
        return; \
     }
    
    // NOW...
    result = InsertData( temperature);
    
    DO_ERROR_CHECK
    
    // and so on InsertData(....)
    
    DO_ERROR_CHECK
    Sometime I split such operation in two functions to separate and avoid repeating the message everywhere in the code.
    Code:
    DoOperation()
    {
       result = InsertAllData();
    
       if (result == false)
          AfxMessageBox("An error has occured");
    
    }
    
    InsertAllData()
    {
       if (!InsertData( temperature ) )
          return false;
    
       if (!InsertData( pressure ) )
          return false;
    }
    any thoughts? How do you do it?

  2. #2
    Join Date
    Oct 2006
    Location
    Sweden
    Posts
    3,654

    Re: Does error checking make code look ungly?

    Seems like you don't care what goes wrong. You could throw an exception from InsertData when something bad happens. Something like this
    Code:
    try
    {
      InsertData( temperature );
      InsertData( pressure );
    }
    catch(...)
    {
      AfxMessageBox( "An error occured" );
    }
    Debugging is twice as hard as writing the code in the first place.
    Therefore, if you write the code as cleverly as possible, you are, by
    definition, not smart enough to debug it.
    - Brian W. Kernighan

    To enhance your chance's of getting an answer be sure to read
    http://www.codeguru.com/forum/announ...nouncementid=6
    and http://www.codeguru.com/forum/showthread.php?t=366302 before posting

    Refresh your memory on formatting tags here
    http://www.codeguru.com/forum/misc.php?do=bbcode

    Get your free MS compiler here
    https://visualstudio.microsoft.com/vs

  3. #3
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Does error checking make code look ungly?

    I use exception handling and throw exceptions.

    Code:
    try
    {
      InsertData( temperature );
    
      InsertData( pressure );
    
      ...
    }
    catch( CMyException& e )
    {
      AfxMessageBox( ..., e.Message );
    }

  4. #4
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,637

    Re: Does error checking make code look ungly?

    I agree that exception handling is probably the way to go, but you could write more concise code too.

    Code:
    if(!InsertData( temperature))
    {
       AfxMessageBox("An error occured");
       return;
    }

  5. #5
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,675

    Re: Does error checking make code look ungly?

    In the particular case of your example you can even write something like this:

    Code:
    if (!InsertData( temperature) ||
    	!InsertData( pressure ) ||
    	!InsertData( location ) ||
    	!InsertData( .... )
    ) {
       AfxMessageBox("An error occured");
       return;
    }
    But your real-life scenario may be more complex, not allowig that brutally simple approach.

    Moreover, at least older compilers may have failed complaining about a single expression being too complex if you go too far with something like that.

    There has, BTW, recently been an IMO interesting thread about that very topic over there in the Non-VC++ forum, discussing various options, even including the malicious goto...
    Last edited by Eri523; May 26th, 2011 at 12:30 PM. Reason: Typo
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  6. #6
    Join Date
    Nov 2000
    Location
    Voronezh, Russia
    Posts
    6,633

    Re: Does error checking make code look ungly?

    To qualify to nice or ugly, it appears very personal.
    As for me this DO_ERROR_CHECK is ugly indeed:
    Code:
    // NOW...
    result = InsertData( temperature);
    
    DO_ERROR_CHECK
    
    // and so on InsertData(....)
    
    DO_ERROR_CHECK
    ...but I have nothing against
    Code:
    result = InsertData( temperature);
    
    if (result == false)
    {
       AfxMessageBox("An error occured");
       return;
    }
    
    result = InsertData( pressure );
    
    if (result == false)
    {
       AfxMessageBox("An error occured");
       return;
    }
    I met the following approach as well:
    Code:
    #define CHECK(func,res) if (res) res = func; 
    
    bool result = true;
    CHECK( InsertData( temperature ), result )
    CHECK( InsertData( pressure ), result )
    CHECK( InsertData( location ), result )
    if (result == false)
    {
       AfxMessageBox("An error occured");
       return;
    }
    Best regards,
    Igor

  7. #7
    Join Date
    Feb 2003
    Location
    Iasi - Romania
    Posts
    8,244

    Re: Does error checking make code look ungly?

    Although exception handling is sometimes criticized, it allows treating the errors in much more clear and centralized manner than if-else-if-else-if-...-else or call-check-return-call-check-...-return ways.
    Last edited by ovidiucucu; October 19th, 2010 at 05:37 AM.
    Ovidiu
    "When in Rome, do as Romans do."
    My latest articles: https://codexpertro.wordpress.com/

  8. #8
    Join Date
    Feb 2003
    Location
    Iasi - Romania
    Posts
    8,244

    Re: Does error checking make code look ungly?

    Quote Originally Posted by Eri523 View Post
    In the particular case of your example you can even write something like this:

    Code:
    if (!InsertData( temperature) ||
    	!InsertData( pressure ) ||
    	!InsertData( location ) ||
    	!InsertData( .... )
    )
    I have often meet such type of "economy class" code. Luckily, I have not a gun...
    Ovidiu
    "When in Rome, do as Romans do."
    My latest articles: https://codexpertro.wordpress.com/

  9. #9
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,637

    Re: Does error checking make code look ungly?

    Quote Originally Posted by ovidiucucu View Post
    I have often meet such type of "economy class" code. Luckily, I have not a gun...
    I don't have a problem with that. What bothers you about it?

  10. #10
    Join Date
    Aug 2006
    Posts
    515

    Re: Does error checking make code look ungly?

    Thank you all, I really liked all the replies. I agree exceptions are the best way to go but Igor's suggestion is quite innovative as well and other suggestions are also plausible. In my case the InsertData function is in dll which doesn't throw exceptions so I have to rely on the return value only.
    Quote Originally Posted by Igor Vartanov
    To qualify to nice or ugly, it appears very personal.
    As for me this DO_ERROR_CHECK is ugly indeed:
    I agree and its not really that readable either but I wanted to explore.

  11. #11
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Does error checking make code look ungly?

    Quote Originally Posted by zspirit View Post
    In my case the InsertData function is in dll which doesn't throw exceptions so I have to rely on the return value only.
    You still can still use exceptions. Simply wrap the dll function call with a class that exposes a static method that checks the return and throws an exception.

    Code:
    try
    {
      DllExceptionWrapper::InsertData( temperature );
    
      DllExceptionWrapper::InsertData( pressure );
      ...
    }
    catch( CMyException& e )
    {
      AfxMessageBox( ..., e.Message );
    }

  12. #12
    Join Date
    Aug 2006
    Posts
    515

    Re: Does error checking make code look ungly?

    Quote Originally Posted by Arjay View Post
    You still can still use exceptions. Simply wrap the dll function call with a class that exposes a static method that checks the return and throws an exception.

    Code:
    try
    {
      DllExceptionWrapper::InsertData( temperature );
    
      DllExceptionWrapper::InsertData( pressure );
      ...
    }
    catch( CMyException& e )
    {
      AfxMessageBox( ..., e.Message );
    }
    That's a great way to come around it. Say I am writing that library or dll or have access to the code, is it good idea to raise exception in the library functions? I see a trade off. Some client appilcation of the library may not want to use exception dependong on their limited use but client application risk failure if exceptions are not handled. Is wrapping them around with wrapper APIs or a class is rather better idea than raising exception in the original dll?

    I am actually thinking more along side general rule now (but still making this problem as en example) and wonder if raising exception is good in a standalone library functions. Only concern I see is client application must handle those exception or risk failure and how they know which function raises which exception? MUST have documentation I guess?

  13. #13
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Does error checking make code look ungly?

    I generally only export C-style functions from a dll and never classes.

    I also never throw exceptions on the dll level and the functions only ever return error codes.

    Actually I do throw exceptions within the dll but these exceptions are caught from within and never cross the function boundary (so the consuming app doesn't need to catch any exceptions thrown by the dll).

    For error passing, I usually adopt the COM error approach so each dll function returns an HRESULT.

    That's what I do on the dll side of things.

    On the app side of things, I like to deal with exceptions because I feel it makes the code easier to read, and error conditions are more easily cleaned up. I follow a C++ style of programming where cleanup is performed in destructors.

    When I call the dll, I usually create a wrapper class that takes the dll HRESULTS and turns them into exceptions. Since the wrapper class and exceptions are defined on the app level, I get to control all of these from within the app.

  14. #14
    Join Date
    Aug 2006
    Posts
    515

    Resolved Re: Does error checking make code look ungly?

    Quote Originally Posted by Arjay View Post
    I generally only export C-style functions from a dll and never classes.

    I also never throw exceptions on the dll level and the functions only ever return error codes.....
    Thanks Arjay, your points well taken. In my case the dll exposes a class, so can't really provide a wrapper in application class but maybe I can drive from it in the dll itself and expose both classes?

    For the sake of example, assume the pseudo code:
    Code:
    CarInDll *car;
    Inventory.CreateCar( &car );
    car->SetMake("BMW");
    car->SetColor(BROWN);
    car->SetYear(2010);
    car->SetCondition("Excellent");
    car->SetSalePrice(40,000);
    Inventory.AddCar( &car );
    I don't think I can do anything to wrap member functions of a class in application. Should I just derive another class in dll and also expose it which now is derived from the same basic export class but this one throws exceptions instead of error values like:
    Code:
    ...in dll code now...
    class CarWithException : public Car
    {
    void SetColor()
      {
        if (! Car::SetColor() )
          throw("requested color not available");
      }
    }

  15. #15
    Join Date
    Nov 2007
    Posts
    35

    Re: Does error checking make code look ungly?

    Since AfxMessageBox() returns an int you could change your function from void to int return type. Then get a single line exit by

    Code:
    if(! result)
      return AfxMessageBox(ErrorMsg)

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured