Don't like ads? PRO users don't see any ads ;-)
Guest

Exception Example

By: a guest on Apr 29th, 2012  |  syntax: C++  |  size: 0.83 KB  |  hits: 21  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #include <iostream>
  2. #include <stdexcept>
  3.  
  4. using namespace std;
  5.  
  6. void doSomething(int);
  7. void doSomethingElse(int);
  8.  
  9. int main()
  10. {
  11.     try
  12.     {
  13.         cout << "doSomething(5);" << endl;
  14.         doSomething(5);
  15.         cout << "doSomething(11);" << endl;
  16.         doSomething(11);
  17.     }
  18.     catch (invalid_argument e)
  19.     {
  20.         cerr << "Error: " << e.what() << endl;
  21.     }
  22.    
  23.     try
  24.     {
  25.         cout << "doSomething(0);" << endl;
  26.         doSomething(0);
  27.     }
  28.     catch (invalid_argument e)
  29.     {
  30.         cerr << "Error: " << e.what() << endl;
  31.     }    
  32.     return 0;
  33. }
  34.  
  35. void doSomething(int x)
  36. {
  37.     if (x > 10)
  38.         throw invalid_argument("X is greater than 10.");
  39.     doSomethingElse(x);
  40. }
  41.  
  42. void doSomethingElse(int x)
  43. {
  44.     if (x == 0)
  45.         throw invalid_argument("X is equal to 0.");
  46. }