Chapter 6. Exception Handling and Stream I - O

Download as pdf or txt
Download as pdf or txt
You are on page 1of 38

CHAPTER 6

Exception Handling and Stream I/O


Er. Ganga Gautam

8/2/2023 Object Oriented Design, OOP in C++ 1


Outline
• Exception Handling:
– Error and Exception,
– Exception Handling Mechanism (try, throw, and
catch),
– Multiple Exception Handling
• File Handling:
– Stream Class Hierarchy,
– Opening and Closing a File,
– Reading and Writing Object

8/2/2023 Object Oriented Design, OOP in C++ 2


Errors and Exception
Errors can be broadly categorized into two types.
– Compile Time Errors
– Run Time Errors
• Compile Time Errors – Errors caught during compiled time is
called Compile time errors. Compile time errors include library
reference, syntax error or incorrect class import.
• Run Time Errors - They are also known as exceptions. An
exception caught during run time creates serious issues.

8/2/2023 Template & Generic Programming, OOP in C++ 3


Exception
• An exception is a problem that arises during the execution of
a program.
• A C++ exception response to an exceptional circumstance that
arises while a program is running, such as an attempt to
divide by zero.
• Exceptions provide a way to transfer control from one part of
a program to another.
• C++ exception handling is built upon three keywords: try,
catch, and throw.

8/2/2023 Template & Generic Programming, OOP in C++ 4


Keyword used for Exception handling
Keywor Purpose
ds
try • The code which can throw any exception is kept inside (or
enclosed in) a try block.
• Then, when the code will lead to any error, that error/exception
will get caught inside the catch block.
catch • catch block is intended to catch the error and handle the
exception condition.
• We can have multiple catch blocks to handle different types of
exception and perform different actions when the exceptions
occur.
• For example, we can display descriptive messages to explain
why any particular exception occurred.
throw • It is used to throw exceptions to exception handler i.e. it is used
to communicate information about error.
• A throw expression accepts one parameter and that parameter
8/2/2023 is passed to handler.
Template & Generic Programming, OOP in C++ 5
Exception Handling
Syntax: Example:

8/2/2023 Template & Generic Programming, OOP in C++ 6


Sample Program 6.13
WAP to illustrate exception handling when divide by a zero.

When we enter 10 and 5, result is displayed.

When we enter 10 and 0, exception is caught and


message is thrown.

8/2/2023 Template & Generic Programming, OOP in C++ 7


Sample Program 6.15
WAP to take age of voter from user and check if he/she is eligible to vote or not. The voter
should be 18 years or above to vote. Your program should handle the exception case for not
being able to vote.
Output: When we 18 or more.

Output: When we put age less than 18

8/2/2023 Template & Generic Programming, OOP in C++ 8


Sample Program 6.14
WAP to illustrate exception handling for array index out of size of the array.

Output: When we put 4 or less.

Output: When we put 5 or above

8/2/2023 Template & Generic Programming, OOP in C++ 9


Multiple Catch blocks
• In some cases, more than one exception could
be raised by same piece of code in a program. General Syntax:
• To handle different types of situations, we can
specify two or more catch blocks, each catching
a different type of exception.
• When an exception is thrown, each catch
statement is inspected in order, and the first
one whose type matches with that of
exception, is executed.
• After one catch statement executes, the others
are bypassed and execution continues after
try/catch block.

8/2/2023 Template & Generic Programming, OOP in C++ 10


Sample Program 6.16
WAP to illustrate multiple exception handling (divide by zero and arraysize out of range).

char

int

Output: When we input two numbers: 10 and 0 and array index:3

400;

Output: When we input two numbers: 10 and 5 and array index:5

8/2/2023 Template & Generic Programming, OOP in C++ 11


File Handling
• File handling is used to store data
permanently in a computer.
• Using file handling we can store our data
in secondary memory (Hard disk).
Stream class Hierarchy
• Streams in C++ are used for handling
input and output operations.
• Stream classes are organized in a
hierarchy based on their functionality.
• The two main categories are: Input
Stream and Output Stream.
Input Stream
• Derived from ios class (base class for I/O
streams).
• Used for reading data from a source (e.g.,
files, keyboard input).
• Examples: istream, ifstream, istringstream.
Output Stream
• Also derived from ios class.
• Used for writing data to a destination (e.g.,
files, console).
• Examples: ostream, ofstream,
ostringstream.
• ofstream: This Stream class signifies the output
file stream and is applied to create files for
writing information to files
• ifstream: This Stream class signifies the input file
stream and is applied for reading information
from files
• fstream: This Stream class can be used for both
read and write from/to files.
File Handling in C++
• To work with files in C++, include the
<fstream> header.
• File handling involves the following steps:
• Opening a file.
• Reading/Writing data to/from the file.
• Closing the file.
Opening a File
We can open a file using any one of the following
methods:
1. First is bypassing the file name in constructor at the
time of object creation.
2. Second is using the open() function.
Syntax:
void open(const char* file_name,ios::openmode
mode);
File opening modes:
Default Open Modes :
• ifstream ios::in
• ofstream ios::out
• fstream ios::in | ios::out

Example:
fstream new_file;
new_file.open(“newfile.txt”, ios::out);
• Using a stream insertion operator << we can write
information to a file
• Using stream extraction operator >> we can easily
read information from a file.
Example of opening/creating a file using the open() function

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file",ios::out);
if(!new_file)
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
new_file.close();
}
return 0;
}
Writing to a File
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file_write.txt",ios::out);
if(!new_file)
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
new_file<<"Learning File handling"; //Writing to file
new_file.close();
}
return 0;
}
Reading from a File
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file_write.txt",ios::in);
if(!new_file)
cout<<"No such file"; } else { char ch; while (!new_file.eof()) { new_file
>>ch;
cout << ch;
}
new_file.close();
return 0;
}
Close a File
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file.txt",ios::out);
new_file.close();
return 0;
}
Practise:
• Create a file “Welcome.txt” and “write
welcome to file handling in C plus plus” and
then read the file content.
Reading and Writing Object
• read data from files into class objects
• write data in class objects to files.
Writing class object to the file
class_name obj;
ofstream file1;
file1.open( “file_name”, ios::app );
file1.write( (char*)&obj, sizeof(obj) );

Here,
• data present in class object obj is written to file
specified file by calling write function.
• (char*)&obj is used to point at the start of an object.
• sizeof(obj) calculates the number of bytes copied in
file.
Reading class object to the file
class_name obj2;
ifstream file2;
file2.open( “file_name”, ios::in );
file2.read( (char*)&obj2, sizeof(obj2) );

Here,
• data present in class object obj2 is read from file
specified by calling read function.
• (char*)&obj2 is used to point at the start of an object
and
• sizeof(obj2) calculates the number of bytes to read
from the file.
#include <iostream>
#include <fstream>
#include<string.h>
using namespace std;
class Student {
public:
char Name[20];
int Student_ID;
int age;
};
int main(){
Student std;
Strcpy(std.Name, "John”);
std.Student_ID=2121;
std.age=11000;

//Writing this data to Student.txt


ofstream file1;
file1.open(”Student.txt”, ios::app);
file1.write((char*)&std,sizeof(std));
file1.close();

//Reading data from Student.txt


Ifstream file2;
file2.open(”Student.txt",ios::in);
file2.seekg(0);
file2.read((char*)&std,sizeof(std));
cout<<“\nName :”<<std.Name;
cout<<"\nStudent ID :”<<std.Student_ID;
cout<<"\nAge:”<<std.age;
file2.close();
return 0;
}
#include <iostream>
#include <fstream>
#include<string.h>
using namespace std;
class Person {
private:
char Name[20];
float weight;
int age;
Public:
void get_info()
{
cout<<“Enter name, weight and age: ”;
cin>>Name>>weight>>age;
}
};
int main(){
int i;
Person p[2];

//Writing this data to Information.txt


ofstream file1;
file1.open(” Information.txt”, ios::app);
for(i=0;i<2;i++)
{
p[i].get_info();
file1.write((char*)&p[i],sizeof(p[i]));
}
file1.close();

//Reading data from Information.txt


Ifstream file2;
file2.open(”Information.txt",ios::in);
file2.seekg(0);
cout<<“Name\t”<<“ weight\t” <<“ age”;
for(i=0;i<2;i++)
{
file2.read((char*)&p[i],sizeof(p[i]));
cout<<“……………………………………”;
cout<<p[i].Name<<“\t”<<p[i].weight<<“\t”<<p[i].age;
}
file2.close();
return 0;
• Assume that you have a class called
”Employee" with the following attributes:
name , age , and occupation . Implement
the necessary functions to allow the user
to input data for multiple Employee objects
and store them in a file ’Details.txt’.
Additionally, provide functionality to read
and display the stored Employee objects
from the file.
#include <iostream>
#include <fstream>
#include<string.h>
using namespace std;
class Employe {
private:
char Name[20];
char occupation[50];
int age;
Public:
void get_info()
{
cout<<“Enter name, occupation and age: ”;
cin>>Name>> occupation >>age;
}
void set_info()
{
Cout<<Name<<“\t”<< occupation<<“\t” <<age<<endl;
}
};
int main(){
int i;
Employe e[2];

ofstream file1;
file1.open(” Details.txt”, ios::out);
for(i=0;i<2;i++)
{
p[i].get_info();
file1.write((char*)&e[i],sizeof(e[i]));
}
file1.close();

Ifstream file2;
file2.open(”Details.txt",ios::in);
file2.seekg(0);
cout<<“Name\t”<<“ Occupation\t” <<“ age”<<endl;
for(i=0;i<2;i++)
{
file2.read((char*)&e[i],sizeof(e[i]));
cout<<“……………………………………”;
p[i].set_info();
}
file2.close();

return 0;
}
• Create a class called book having a member
name, price, author and pages. Create a file
called ‘’Library.docx” and store record of 500
books. Now, read the file to print the
information of the book which is above 300.
• A class called ”student" has the following
attributes: roll number, name , age , and
address . Implement the necessary
functions to allow the user to display for
100 student objects from file
’StudentInfo.txt’.
#include <iostream>
#include <fstream>
#include<string.h>
using namespace std;
class Student {
private:
char Name[20];
char add[50];
int age;
Int roll;
public:
void set_info()
{
Cout<<Name<<“\t”<<add<<“\t”<< age<<“\t” <<roll<<endl;
}
};
int main(){
int i;
Student e[100];

Ifstream file2;
file2.open(”studentInfo.txt",ios::in);

if(!new_file)
{
cout<<"No such file";
}
else
{
file2.seekg(0);
cout<<“Name\t”<<“ address\t” <<“ age”<<“\t”<<roll<<endl;
for(i=0;i<100;i++)
{
file2.read((char*)&e[i],sizeof(e[i]));
cout<<“……………………………………”;
p[i].set_info();
}
}
file2.close();

return 0;
}
End of chapter 6

8/2/2023 Object Oriented Design, OOP in C++ 38

You might also like