Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) try

 

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.

 

The code below shows the function CanLexicalCast, which returns true if a certain std::string can be converted to another data type (an int, for example). The risky operation, the conversion, is put in the try-block.

 

#include <cassert>
#include <string>
#include <boost/lexical_cast.hpp>
 
//From http://www.richelbilderbeek.nl/CppCanLexicalCast.htm
template <class TargetType>
bool CanLexicalCast(const std::string& from)
{
  try
  {
    boost::lexical_cast<TargetType>(from);
  }
  catch (boost::bad_lexical_cast)
  {
    return false;
  }
  catch (...)
  {
    assert(!"Something unexpected happened");
    throw;
  }
  return true;
}

 

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'

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict