Exceptions: Difference between revisions

C++ removed deprecated throw() specification; reworded
(C++ removed deprecated throw() specification; reworded)
Line 665:
=={{header|C++}}==
 
TheIn 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'''
Line 676 ⟶ 673:
};</lang>
 
There'sHowever alsothrown aexceptions classshould almost always derive from <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 also derive from <tt>std::exception</tt>.
 
<lang cpp>#include <exception>
struct MyException: std::exception
{
charvirtual const char* what() const throw()noexcept { return "description"; }
}</lang>
 
Note that in principle you can throw any copyable type as exception, including built-in types.
 
'''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();
125

edits