C++ examples for Statement:try catch
Nesting try Blocks
#include <iostream> #include <fstream> #include <cstdlib> #include <string> using namespace std; int main()// w w w.ja va 2s .c om { string fileOne = "info.txt"; string fileTwo = "info.bak"; char ch; ifstream inFile; ofstream outFile; try { inFile.open(fileOne.c_str()); if (inFile.fail()) throw fileOne; try { outFile.open(fileTwo.c_str()); if (outFile.fail()) throw fileTwo; while ((ch = inFile.get()) != EOF) outFile.put(ch); inFile.close(); outFile.close(); } // end of inner try block catch(string out) // catch for inner try block { cout << "The backup file " << out << " was not successfully opened." << endl; exit(1); } } catch(string in) // catch for outer try block { cout << "The input file " << in << " was not successfully opened." << endl << " No backup was made." << endl; exit(1); } cout << "A successful backup of " << fileOne << " named " << fileTwo << "was successfully made." << endl; return 0; }