0% found this document useful (0 votes)
3 views13 pages

unit-4 c--

This document covers exception handling and stream computation in C++. It explains the concept of exceptions, their types, and techniques for handling them in C++, alongside examples of stream computation with console and file operations. It also details file handling best practices, including reading and writing operations, and the importance of error checking.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views13 pages

unit-4 c--

This document covers exception handling and stream computation in C++. It explains the concept of exceptions, their types, and techniques for handling them in C++, alongside examples of stream computation with console and file operations. It also details file handling best practices, including reading and writing operations, and the importance of error checking.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Unit 4: Exception Handling, Stream Computation

1. Concept of Exception Handling,


2. Types of Exception,
3. Exception Handling Techniques,
4. Stream Computation with console,
5. Streams Computations with Files,
6. Read and write operations on file.

Concept of Exception Handling


Exception handling is a mechanism in programming that
deals with runtime errors, allowing a program to continue running
rather than crashing abruptly. The goal is to gracefully handle
errors and maintain normal program flow.

Core Components of Exception Handling in C++


1. try block
Contains code that may throw an exception.
2. throw statement
Used to signal (or "throw") an exception when an
error occurs.

© [2025] Naina Sonar


3. catch block
Handles the exception thrown in the try block.
Multiple catch blocks can be used to handle different
types of exceptions.

Basic Syntax:
try {
// Code that may cause an exception
if (denominator == 0)
throw "Division by zero error!";
int result = numerator / denominator;
}
catch (const char* message) {
// Code to handle the exception
std::cout << "Error: " << message << std::endl;}

© [2025] Naina Sonar


Example Program:
#include <iostream>
using namespace std;

int main() {
int numerator = 10;
int denominator;

cout << "Enter denominator: ";


cin >> denominator;

try {
if (denominator == 0)
throw "Division by zero is not allowed!";
cout << "Result: " << numerator / denominator
<< endl;
}
catch (const char* msg) {
cout << "Error: " << msg << endl;
}

cout << "Program continues after exception handling."


<< endl;
return 0;
}
Key Points
• C++ allows throwing and catching any type (int,
char*, objects, etc.).
• Always catch exceptions by reference or const
reference for efficiency and correctness.
• You can have multiple catch blocks for different
exception types.

© [2025] Naina Sonar


Keyword Meaning Simple Example
Try Wraps code that might try { int x = 10 / y;
throw an exception }
(Start of risky code)
throw Signals an exception throw "Error!";
when an error occurs
(Send an error
message)
catch Catches and handles catch (const char*
the thrown exception e) { cout << e; }
(Handle the thrown
error)
Types of Exception:
What is an Exception in C++?
An exception is a runtime error or an unexpected event
that occurs while a program is running, which disrupts
the normal flow of instructions.
Simple Definition:
An exception is an object or value that signals an error or
unexpected situation in a program.

Example of Exceptions:
• Dividing by zero
• Accessing an invalid array index
• Memory allocation failure
• Opening a file that doesn’t exist

Why Use Exceptions?


• To prevent program crash
• To handle errors gracefully
• To separate error handling from main logic

© [2025] Naina Sonar


Without Exception Handling:
int a = 10, b = 0;
int c = a / b; // This will crash the program
With Exception Handling:
try {
int a = 10, b = 0;
if (b == 0)
throw "Cannot divide by zero!";
int c = a / b;
}
catch (const char* msg) {
cout << "Error: " << msg;
}
Common Standard Exceptions
(from <stdexcept>)
Exception Class Meaning
std::exception Base class for all standard
exceptions
std::runtime_error Generic runtime error
std::logic_error Logic errors in the program
std::out_of_range Accessing outside valid range
std::bad_alloc Memory allocation failure
std::invalid_argument Invalid function argument
Types of Exceptions in C++
Type Description Example
1. Standard Built-in exceptions std::logic_error,
Exceptions in the C++ std::runtime_error
Standard Library
(<exception> or
<stdexcept>).
Covers common
errors.

© [2025] Naina Sonar


2. Derived More specific std::out_of_range
Exceptions exceptions derived (from
from standard std::logic_error)
ones.
3. User- Created by the class MyException
Defined programmer to {}
Exceptions handle custom
errors in an
application.
Exception Handling Techniques in C++

Technique Description Example


try-catch Wrap risky try { ... } catch(...) { ...
block code in try, and }
handle errors in
catch.
Multiple Use different catch(int e),
catch catch blocks for catch(const char* e)
blocks different error
types.
Catch all Use catch(...) catch(...) { cout <<
exceptions to catch any "Unknown error"; }
type of
exception.
Throwing Use throw to throw "Error occurred!";
exceptions signal an error
in code.
Rethrowing Use throw; catch(...) { throw; }
exceptions inside a catch
to pass the
exception to
another

© [2025] Naina Sonar


handler.
User- Create custom class MyException :
defined classes to public exception {}
exceptions represent
specific errors.
Using Use predefined throw
standard exceptions std::out_of_range("Out
exceptions from of range");
<stdexcept> or
<exception>.

Stream Computation with Console :


Stream computation with the console in C++
involves taking input from the user using input streams
and displaying output using output streams. This is done
through the cin and cout streams provided by the
<iostream> header.
Common C++ Streams:

Stream Purpose Usage


cin Input from keyboard cin >> variable;
cout Output to console cout << "text";
cerr Output for errors cerr << "error";
clog Output for logs/info clog << "log";

Simple Example: Stream Computation


#include <iostream>
using namespace std;

int main() {

© [2025] Naina Sonar


int num1, num2, sum;

// Input
cout << "Enter first number: ";
cin >> num1;

cout << "Enter second number: ";


cin >> num2;

// Computation
sum = num1 + num2;

// Output
cout << "Sum = " << sum << endl;

return 0;
}
Explanation:
Step Code Meaning
Input cin >> num1 >> Reads values from the
num2; console
Computation sum = num1 + Performs calculation
num2;
Output cout << sum; Displays result on
screen

Stream Computation with Files:


In C++, file stream operations are handled using file
streams, specifically ifstream for reading and ofstream
for writing to files. These streams allow you to perform
input and output operations, similar to console I/O but
with files.

© [2025] Naina Sonar


File Stream Classes in C++:

Class Purpose Example Use


ifstream Input file stream (for ifstream
reading) inputFile("file.txt");
ofstream Output file stream ofstream
(for writing) outputFile("file.txt");
fstream Both input and `fstream file("file.txt",
output (for reading ios::in
and writing)

Opening and Closing Files


• Files are opened using the constructor of the stream
class.
• Files must be closed using close() after operations
are completed to ensure data is saved.

ifstream inputFile("input.txt"); // Open for reading


ofstream outputFile("output.txt"); // Open for writing

Simple Example: Read and Write File


#include <iostream>
#include <fstream>
using namespace std;

int main() {
int num1, num2, sum;

// Open input and output files


ifstream inputFile("input.txt");
ofstream outputFile("output.txt");

© [2025] Naina Sonar


// Check if file is open successfully
if (!inputFile) {
cerr << "Error opening input file!" << endl;
return 1;
}
if (!outputFile) {
cerr << "Error opening output file!" << endl;
return 1;
}

// Read numbers from file


inputFile >> num1 >> num2;

// Perform computation
sum = num1 + num2;

// Write result to output file


outputFile << "Sum: " << sum << endl;

// Close files
inputFile.close();
outputFile.close();

cout << "Computation complete. Results written to


output.txt." << endl;

return 0;
}

© [2025] Naina Sonar


Explanation:

Step Code Explanation


Open files ifstream Opens the
inputFile("input.txt"); input file for
reading
ofstream Opens the
outputFile("output.txt"); output file for
writing
Read from inputFile >> num1 >> Reads values
file num2; from the input
file
Perform sum = num1 + num2; Adds the
computation numbers read
from the file
Write to file outputFile << sum; Writes the
result to the
output file
Close files inputFile.close(); Closes both
the input and
output files

Read and Write Operations on Files :


Required Header
File handling in C++ allows programs to store data
permanently by reading from or writing to files (instead
of working only with temporary data in memory).
C++ provides the <fstream> header with three main
classes for file handling:

#include <fstream> // For file handling

© [2025] Naina Sonar


File Modes in C++
Mode Description
ios::in Open for reading
ios::out Open for writing (overwrites file)
ios::app Append to the end of the file

Best Practices
• Always check if the file was opened successfully.
• Close files after use.
• Use getline() for reading entire lines (especially if
input includes spaces).

Class Purpose
ifstream Input file stream (for reading)
ofstream Output file stream (for writing)
fstream File stream for both reading and writing

Steps for File Handling in C++


1. Include the <fstream> header.
2. Create an object of ifstream, ofstream, or fstream.
3. Open the file using constructor or open() method.
4. Check if file is open using .is_open() or just by
evaluating the object.
5. Perform read/write operations.
6. Close the file using .close().

Write Operation:
To write data to a file:
• Use ofstream or fstream with ios::out or ios::app.
• Use << operator to insert data.

© [2025] Naina Sonar


ofstream file("example.txt");
file << "Hello World!";
file.close();
Read Operation
To read data from a file:
• Use ifstream or fstream with ios::in.
• Use >> to read word by word or getline() to read a
full line.
ifstream file("example.txt");
string line;
while (getline(file, line)) {
cout << line;
}
file.close();
Error Checking
Always check if a file is opened successfully before
performing operations:
ifstream file("data.txt");
if (!file.is_open()) {
cerr << "Error: File could not be opened!";
}
Closing Files
Always close a file after use:
file.close();
This flushes any remaining output and frees system
resources.
Advantages of File Handling
• Stores data permanently
• Allows reading large data efficiently
• Enables data transfer between programs
• Useful for logs, backups, databases, etc.

© [2025] Naina Sonar

You might also like