(C++) catch
January 3, 2018 ยท View on GitHub
catch is a keyword to mark a catch-block. A catch-block is always preceded by a try-block in which an exception might be thrown. The exception can be caught by the subsequent catch-block.
Example: std::stoi
std::stoi converts a std::string to integer
std::stoi example: input can be converted to integer
#include <cassert>
#include <string>
int main()
{
assert(std::stoi("123") == 123);
}
std::stoi example: input is no integer
If the input cannot be converted to integer, a std::invalid_argument is thrown.
#include <cassert>
#include <stdexcept>
#include <string>
int main()
{
try
{
std::stoi("this is no int");
assert(!"Should not get here");
}
catch (const std::invalid_argument&)
{
assert("OK");
}
}
std::stoi example: input is a too big integer
If the input is a too big integer, a std::out_of_range is thrown.
#include <cassert>
#include <stdexcept>
#include <string>
int main()
{
try
{
std::stoi("12345678901234567890123456789012345678901234567890");
assert(!"Should not get here");
}
catch (const std::out_of_range&)
{
assert("OK");
}
}
std::stoi example: handle both exceptions
#include <cassert>
#include <stdexcept>
#include <string>
int main()
{
try
{
std::stoi("[your string here]");
assert(!"Should not get here");
}
catch (const std::invalid_argument&)
{
assert("OK");
}
catch (const std::out_of_range&)
{
assert("OK");
}
}
As an alternative, the base of both exceptions (called std::exception) can be used:
#include <cassert>
#include <stdexcept>
#include <string>
int main()
{
try
{
std::stoi("[your string here]");
assert(!"Should not get here");
}
catch (const std::exception&)
{
assert("OK");
}
}
Advice
- Don't try to catch every exception in every function [1]
- Always catch by reference[3], for example
const std::invalid_argument& - Have main catch and report every exception [2]
Reference
- [1] Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 13.7. Advice. page 387: '[8] 'Don't try to catch every exception in every function'
- [2] Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 13.7. Advice. page 387: '[27] 'Have main() catch and report every exception'
- [3] Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 30.5. Advice. page 883: '[10] Always catch exception& (for standard-library and language support exceptions) and ... (for unexpected exceptions)'