unit-4 c--
unit-4 c--
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;}
int main() {
int numerator = 10;
int 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;
}
Example of Exceptions:
• Dividing by zero
• Accessing an invalid array index
• Memory allocation failure
• Opening a file that doesn’t exist
int main() {
// Input
cout << "Enter first number: ";
cin >> num1;
// 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
int main() {
int num1, num2, sum;
// Perform computation
sum = num1 + num2;
// Close files
inputFile.close();
outputFile.close();
return 0;
}
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
Write Operation:
To write data to a file:
• Use ofstream or fstream with ios::out or ios::app.
• Use << operator to insert data.