C++ Exception Handling: Advantage
C++ Exception Handling: Advantage
In C++, exception is an event or object which is thrown at runtime. All exceptions are
derived from std::exception class. It is a runtime error which can be handled. If we don't
handle the exception, it prints exception message and terminates the program.
Advantage
It maintains the normal flow of the application. In such case, rest of the code is executed
even after exception.
Exception Description
o try
o catch, and
o throw
Moreover, we can create user-defined exception which we will learn in next chapters.
C++ try/catch
In C++ programming, exception handling is performed using try/catch statement. The C+
+ try block is used to place the code that may occur exception. The catch block is used to
handle the exception.
Output:
Output:
To read and write from a file we are using the standard C++ library called fstream. Let us
see the data types define in fstream library is:
fstream It is used to create files, write information to files, and read information from files.
1. #include <iostream>
2. #include <fstream>
3. using namespace std;
4. int main () {
5. ofstream filestream("testout.txt");
6. if (filestream.is_open())
7. {
8. filestream << "Welcome to javaTpoint.\n";
9. filestream << "C++ Tutorial.\n";
10. filestream.close();
11. }
12. else cout <<"File opening is fail.";
13. return 0;
14. }
Output:
1. #include <iostream>
2. #include <fstream>
3. using namespace std;
4. int main () {
5. string srg;
6. ifstream filestream("testout.txt");
7. if (filestream.is_open())
8. {
9. while ( getline (filestream,srg) )
10. {
11. cout << srg <<endl;
12. }
13. filestream.close();
14. }
15. else {
16. cout << "File opening is fail."<<endl;
17. }
18. return 0;
19. }
Note: Before running the code a text file named as "testout.txt" is need to be created and
the content of a text file is given below:
Welcome to javaTpoint.
C++ Tutorial.
Output:
Welcome to javaTpoint.
C++ Tutorial.
1. #include <fstream>
2. #include <iostream>
3. using namespace std;
4. int main () {
5. char input[75];
6. ofstream os;
7. os.open("testout.txt");
8. cout <<"Writing to a text file:" << endl;
9. cout << "Please Enter your name: ";
10. cin.getline(input, 100);
11. os << input << endl;
12. cout << "Please Enter your age: ";
13. cin >> input;
14. cin.ignore();
15. os << input << endl;
16. os.close();
17. ifstream is;
18. string line;
19. is.open("testout.txt");
20. cout << "Reading from a text file:" << endl;
21. while (getline (is,line))
22. {
23. cout << line << endl;
24. }
25. is.close();
26. return 0;
27. }
Output: