The out_of_range C++ exception handling program example

 

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info:

To do: Try to catch the invalid string position for exception handling in C++

To show: The out_of_range C++ code example

 

// The out_of_range C++ program example

#include <string>

#include <iostream>

using namespace std;

 

int main(void)

{

try

{

string strg1("Test");

string strg2("ing");

strg1.append(strg2, 4, 2);

cout<<strg1<<endl;

}

 

catch (exception &e)

{

cerr<<"Caught: "<<e.what()<<endl;

cerr<<"Type: "<<typeid(e).name()<<endl;

};

return 0;

}

 

Output example:

 

Caught: invalid string position

Type: class std::out_of_range

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index