Exceptions: Difference between revisions

Content added Content deleted
(→‎Defining exceptions: std::exception as base class, and a note)
Line 177: Line 177:


===Defining exceptions===
===Defining exceptions===
<cpp>
struct MyException
struct MyException
{
{
// data with info about exception
// data with info about exception
};
};
</cpp>

There's also a class <code>std::exception</code> which you can, but are not required to derive your exception class from. The advantage of doing so is that you can catch unknown exceptions and still get some meaningful information out. There are also more specific classes like <code>std::runtime_error</code> which derive from <code>std::exception</code>.

<cpp>
#include <exception>
struct MyException: std::exception
{
char const* what() const throw() { return "description"; }
}
</cpp>

Note that in principle you can throw any copyable type as exception, including built-in types.


===Throw exceptions===
===Throw exceptions===