Exceptions: Difference between revisions

Content added Content deleted
(C++ removed deprecated throw() specification; reworded)
Line 665: Line 665:
=={{header|C++}}==
=={{header|C++}}==


In C++ an exception can be of any copyable type, this includes int's, other primitives, as well as objects.
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.

The exception can be of any type, this includes int's, other primitives, as well as objects.


'''Defining exceptions'''
'''Defining exceptions'''
Line 676: Line 673:
};</lang>
};</lang>


There's also a class <tt>std::exception</tt> 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 <tt>std::runtime_error</tt> which derive from <tt>std::exception</tt>.
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
{
{
char const* what() const throw() { return "description"; }
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>void foo()
<lang cpp>// this function can throw any type of exception
void foo()
{
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();