CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jan 2009
    Posts
    4

    Question Easily create string message for exception

    Hi,
    For a long time I’ve wondered if there is a simplier way to do this, but I’ve never found it. If I have the following code:

    Code:
    void SomeClass::SomeMethod(const char *arg) {
       If (someTestOfTheArgFailed)
          throw std::invalid_argument (“Invalid argument ‘” + arg + “’”);
    }
    Now obviously the above code doesn’t work, because I can’t do “Invalid argment ‘” + arg. The alternative would be to do:

    Code:
    If (someTestOfTheArgFailed) {
       std::string s;
       s += " Invalid argument '";
       s += arg;
       s += "'";
       throw std::invalid_argument (s);
    }
    This works but has needlessly added extra lines.

    It would be cool if I could use some kind of printf syntax, or use operator<<.

    Is there some clever trick I can use to do this all on one line still? Perhaps a function or macro I could develop? This is just so I can make my error handling code neater. I don't want to have 4-5 lines for each error message.

    Thanks
    Andrew

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Easily create string message for exception

    Code:
    void SomeClass::SomeMethod(const char *arg) {
       If (someTestOfTheArgFailed)
          throw std::invalid_argument (std::string(“Invalid argument ‘”) + arg + “’”);
    }
    I think Boost has something similar to printf that you can use. However, I'd just do the above for starters....

  3. #3
    Join Date
    Aug 2007
    Posts
    858

    Re: Easily create string message for exception

    The easiest way I've found is to make your own exception class that takes a printf style format string and variadic args. I can't recall offhand though if variadic constructors are part of the standard or a MSVC extension...

    Anyway, what I usually use is something like:

    Code:
    #include <stdexcept>
    #include <cstdarg>
    #include <cstdio>
    
    class MyError 
      : public std::runtime_error
    {
    public:
      static const size_t BUFSIZE = 2048;
    
      MyError(const char* format, ...)
        : std::runtime_error("")
      {
        va_list args;
        char buffer[BUFSIZE];
    
        va_start(args, format);
        vsprintf(buffer, format, args);
        va_end(args);
    
        std::runtime_error::operator =(std::runtime_error(buffer));
      }
    };

Tags for this Thread

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