Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) catch

 

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.

 

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;
}

 

 

 

 

 

Advice

 

 

 

 

 

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)'

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict