Topic: throw_assert


Author: "thoth39" <pedro.lamarao@gmail.com>
Date: Tue, 30 May 2006 16:02:27 CST
Raw View
Has this been proposed before?

-- std_throw_assert.hpp --

#if !defined(STD_THROW_ASSERT_HPP)
#define STD_THROW_ASSERT_HPP

#include <sstream>
#include <stdexcept>
#include <string>

#ifdef  NDEBUG

#define throw_assert(e) ((void)0)

#else

namespace std {

    namespace detail {

        std::string
        build_assertion_error (char const* e, char const* file,
unsigned line) {
            std::ostringstream o;
            o << "Assertion failed: " << e << ", file " << file << ",
line " << line;
            return o.str();
        }

    }

    class assertion_error : public std::runtime_error {
    public:

        assertion_error (char const* e, char const* file, unsigned
line)
        : std::runtime_error(detail::build_assertion_error(e, file,
line)) {}

    };

}

#define throw_assert(e) (void)((e) || (throw std::assertion_error(#e,
__FILE__, __LINE__),0))

#endif

#endif // STD_THROW_ASSERT_HPP

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html                      ]





Author: "Bob Bell" <belvis@pacbell.net>
Date: Wed, 31 May 2006 00:36:00 CST
Raw View
thoth39 wrote:
> Has this been proposed before?

[snip description of assertion macro that throws]

Yes it has; personally I think it's a pretty bad idea, for lots of
reasons. Here are some:

   * unwinding the stack when an assertion fails can do more damage as
well as destroy information that might help you understand the failure
   * catch (...) can make the assertion go unnoticed
   * when an assertion fails, you want to execute as little subsequent
code as possible; exceptions make it difficult to limit or control what
subsequent code is executed (e.g., a catch (...) can allow the program
to continue as if nothing happened)
   * throwing when an assertion fails overloads the purpose of
exception handling -- dealing with run-time failures as well as
programmer errors -- making the exception handling design more complex
   * most of the time, an assertion failure corresponds to a local
problem; exceptions transfer control non-locally to an enclosing scope
that can typically do nothing about the problem

See also proposal N1962 at
http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2006/n1962.html.

Bob

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html                      ]