Exceptions: Difference between revisions
Content added Content deleted
(C++ removed deprecated throw() specification; reworded) |
|||
Line 665: | Line 665: | ||
=={{header|C++}}== |
=={{header|C++}}== |
||
⚫ | |||
C++ has no finally construct. Instead you can do this in the destructor of an object on the stack, which will be called |
|||
if an exception is thrown. |
|||
⚫ | |||
'''Defining exceptions''' |
'''Defining exceptions''' |
||
Line 676: | Line 673: | ||
};</lang> |
};</lang> |
||
However thrown exceptions should almost always derive from <tt>std::exception</tt>. The advantage of doing so is that you can catch unknown exceptions and still get some meaningful information. There are also more specific classes like <tt>std::runtime_error</tt> which also derive from <tt>std::exception</tt>. |
|||
<lang cpp>#include <exception> |
<lang cpp>#include <exception> |
||
struct MyException: std::exception |
struct MyException: std::exception |
||
{ |
{ |
||
virtual const char* what() const noexcept { return "description"; } |
|||
}</lang> |
}</lang> |
||
Note that in principle you can throw any copyable type as exception, including built-in types. |
|||
'''Throw exceptions''' |
'''Throw exceptions''' |
||
⚫ | |||
<lang cpp>// this function can throw any type of exception |
|||
⚫ | |||
{ |
|||
throw MyException(); |
|||
} |
|||
// this function can only throw the types of exceptions that are listed |
|||
void foo2() throw(MyException) |
|||
{ |
|||
throw MyException(); |
|||
} |
|||
// this function turns any exceptions other than MyException into std::bad_exception |
|||
void foo3() throw(MyException, std::bad_exception) |
|||
{ |
{ |
||
throw MyException(); |
throw MyException(); |