Skip to content

Instantly share code, notes, and snippets.

@shelomentsevd
Last active February 11, 2017 19:59
Show Gist options
  • Save shelomentsevd/54fe3fb3ef84c6db1f4f28177c26d8b7 to your computer and use it in GitHub Desktop.
Save shelomentsevd/54fe3fb3ef84c6db1f4f28177c26d8b7 to your computer and use it in GitHub Desktop.
Short note about exceptions in C++
// C++ exceptions short-note
// Example
#include <exception>
class MyException: public std::exception
{
virtual const char * what() const throw()
{
return "Exception's description";
}
};
// Throw
throw MyException();
// Catch
try
{
// Some code
}
catch(MyException & ex)
{
std::cout << ex.what();
// Pass forward
throw;
}
// Catch any exception
catch(...)
{
// Code
}
// What the hell is "throw()" after [function_name]()?
// We expect that foo can throw exceptions
void foo();
// We expect that foo can throw only exceptions type of int(DEPRECATED)
void foo() throw(int);
// We expect that foo can't throw exceptions
void foo() throw();
// Q: So what does happen if two last functions will throw exceptions?
// A: Functions will call std::unexpected or std::terminate.
// If std::unexpected didn't set(you can do it by std::set_unexpected) function calls std::terminate.
// noexcept(since c++11, recomended instead throw())
// We guarantee that foo don't throw exceptions
// if foo() throw exception - std::terminate called
void foo() noexcept;
// Q: Is noexcept useful?
// A: https://akrzemi1.wordpress.com/2014/04/24/noexcept-what-for/
// Best way to use:
if(noexcept(ImportantFunction()))
{ // ImportantFunction guarantee exception safety(http://www.boost.org/community/exception_safety.html)
// do some stuff
}
else
{ // doesn't
// do other stuff
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment