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.
#include <exception>
int main()
{
throw std::exception();
}
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");
}
}
- Throw an exception to indicate that you cannot perform an assigned task [1]
- Let a constructor establish an invariant, and throw if it cannot [2]
- If a function may not throw, declare it noexcept [3]
- [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'