(C++) try
January 3, 2018 ยท View on GitHub
try is a keyword to mark 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
- Minimize the use of try-blocks [1].
Reference
- [1] Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 13.7. Advice. page 387: '[16] 'Minimize the use of try-blocks'