Throwing an exception from a function : Basics « Function « C++






Throwing an exception from a function

Throwing an exception from a function

 
 
#include <iostream> 
using namespace std; 
 
void myFunction(int test) 
{ 
  cout << "Inside myFunction, test is: " << test << endl; 
  if(test) throw test; 
} 
 
int main() 
{ 
  cout << "start\n"; 
 
  try {                           // start a try block 
    cout << "Inside try block\n"; 
    myFunction(0); 
    myFunction(1); 
    myFunction(2); 
  } catch (int i) {              // catch an error 
    cout << "Caught an exception -- value is: "; 
    cout << i << endl; 
  } 
 
  cout << "end"; 
 
  return 0; 
}

           
       








Related examples in the same category

1.Class as a return typeClass as a return type
2.Another example of a conversion functionAnother example of a conversion function
3.Computes the factorial of an integer iteratively: a loop, and recursively
4.A C++ program with several functionsA C++ program with several functions