View Single Post
Old Jan 19th, 2008, 1:54 PM   #4
Jessehk
The Oblivious One
 
Jessehk's Avatar
 
Join Date: May 2005
Location: Ontario, Canada
Posts: 644
Rep Power: 4 Jessehk is on a distinguished road
Re: Exception handling: point is...?

c++ Syntax (Toggle Plain Text)
  1. #include <iostream>
  2. #include <stdexcept>
  3.  
  4. #include <boost/format.hpp> // for easy string building
  5.  
  6. int factorial( int n ) {
  7. if ( n < 0 ) {
  8. using namespace boost;
  9. format errmsg( "Can't compute (%d)!" );
  10. throw std::invalid_argument( (errmsg % n).str() );
  11. }
  12.  
  13. int result = 1;
  14. while ( n != 0 )
  15. result *= n--;
  16.  
  17. return result;
  18. }
  19.  
  20. int main() {
  21. try {
  22. std::cout << factorial( 3 ) << std::endl;
  23. std::cout << factorial( 0 ) << std::endl;
  24. std::cout << factorial( -2 ) << std::endl;
  25. } catch ( std::invalid_argument &e ) {
  26. std::cerr << e.what() << std::endl;
  27. }
  28. }

6
1
Can't compute (-2)!

__________________
Dr. Zoidberg: [ecstatic] I'm going to a movie... with FRIENDS!
Jessehk is offline   Reply With Quote