C++ Exceptions (Exception Handling)
C++ exceptions provide a way to handle runtime errors and exceptional situations in a program. Exception handling allows the programmer to control the flow of the program and handle errors in a more structured way.
Syntax
try {
// code that may throw an exception
}
catch (exception_type e) {
// code to handle the exception
}
The try
block contains the code that may throw an exception. If an exception is thrown, the code in the catch
block is executed.
Example
#include <iostream>
using namespace std;
int main() {
try {
int x = 10;
int y = 0;
if (y == 0) {
throw "Division by zero";
}
int z = x / y;
cout << z << endl;
}
catch (const char* error) {
cout << "Error: " << error << endl;
}
return 0;
}
Output
Error: Division by zero
Explanation
In the above example, we have a try
block containing some code that may throw an exception. If the value of y
is zero, we throw an exception with the message "Division by zero". The catch
block catches the exception and prints the error message to the console.
Use
Exception handling is often used in situations where there may be unexpected errors or exceptional conditions in the program. By catching and handling exceptions, we can prevent our program from crashing or producing unexpected results.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
try {
ifstream file("example.txt");
if (!file.is_open()) {
throw "File not found";
}
string line;
while (getline(file, line)) {
cout << line << endl;
}
}
catch (const char* error) {
cout << "Error: " << error << endl;
}
return 0;
}
In the above example, we are trying to open a file and read its contents. Using exception handling, we can catch the case where the file is not found and handle it gracefully.
Important Points
- C++ exceptions allow programmers to handle runtime errors and exceptional conditions in a program.
- The
try
block contains code that may throw an exception, and thecatch
block catches and handles the exception. - Different types of exceptions can be caught using different
catch
blocks. - Exceptions should only be used for exceptional situations, not as a replacement for regular error handling.
Summary
In summary, exception handling in C++ provides a way to handle runtime errors and exceptional situations in a more structured way. By catching and handling exceptions, we can control the flow of the program and avoid unexpected crashes or errors. However, exceptions should only be used for exceptional situations and not as a replacement for regular error handling.