C++ examples for Statement:try catch
Catch exception with a do-nothing block that permits processing to continue
#include <iostream> #include <fstream> #include <cstdlib> #include <string> #include <iomanip> using namespace std; int main()/*from www . j ava2s . c o m*/ { char response; string filename = "prices.dat"; ifstream inFile; ofstream outFile; try // open a basic input stream to check whether the file exists { inFile.open(filename.c_str()); if (inFile.fail()) throw 1; cout << filename << " currently exists.\nDo you want to overwrite it with the new data (y or n): "; cin >> response; if (tolower(response) == 'n') { inFile.close(); cout << "The existing file has not been overwritten." << endl; exit(1); } } catch(int e) {}; // a do-nothing block that permits processing to continue try { outFile.open(filename.c_str()); if (outFile.fail()) throw filename; outFile << setiosflags(ios::fixed) << setiosflags(ios::showpoint) << setprecision(2); // write the data to the file outFile << "M " << 9.95 << endl << "B " << 3.2 << endl << "A " << 1.08 << endl; outFile.close(); cout << filename << " has been successfully written." << endl; return 0; } catch(string e) { cout << filename << " was not opened for output and has not been written." << endl; } }