Skip to content

Latest commit

 

History

History
62 lines (49 loc) · 2.03 KB

CppThrow.md

File metadata and controls

62 lines (49 loc) · 2.03 KB

throw is the keyword to produce an exception.

A try-block indicates the calling of functions that might throw an exception and is followed by a catch-block, where the exception is handled.

Example: throw an exception

#include <exception>

int main()
{
  throw std::exception();
}

Example: handle exception thrown

std::stoi converts a std::string to int and will throw a std::invalid_argument if that cannot be done.

#include <cassert>
#include <stdexcept>
#include <string>

int main()
{
  try
  {
    std::stoi("this is no int");
    assert(!"Should not get here");
  }
  catch (std::invalid_argument&)
  {
    assert("OK");
  }
}
  • [1] Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 13.7. Advice. page 386: '[2] Throw an exception to indicate that you cannot perform an assigned task'
  • [2] Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 13.7. Advice. page 387: '[11] Let a constructor establish an invariant, and throw if it cannot'
  • [3] Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 13.7. Advice, page 387: '[23] If your function may not throw, declare it noexcept'