Welcome to our deep dive into C++ exception handling! Today, we'll explore the try, catch, and throw keywords that make error handling in your C++ programs a breeze. Let's get started!
Exception handling is a mechanism that allows a program to respond to exceptional or error conditions in a controlled manner. Rather than letting the program crash, it provides a way to handle these errors gracefully, making your code more robust and reliable.
The try, catch, and throw keywords form the cornerstone of exception handling in C++.
The try block encloses the code that may potentially throw an exception.
try {
// Code that may throw an exception
}The catch block is used to handle exceptions that occur within the try block. You can have multiple catch blocks for different types of exceptions.
try {
// Code that may throw an exception
} catch (exception_type identifier) {
// Code to handle the exception
}The throw statement is used to create and throw an exception from within your code.
throw exception_type();To create custom exceptions, derive a new class from std::exception. This new class will serve as your custom exception type.
class CustomException : public std::exception {
public:
const char* what() const throw() {
return "A custom exception has occurred!";
}
};You can then throw this custom exception from your code and catch it using a catch block.
try {
throw CustomException();
} catch (CustomException e) {
std::cerr << e.what() << std::endl;
}Let's consider a simple example of a function that opens a file and reads its contents. If the file doesn't exist, we want to throw an exception.
#include <fstream>
#include <stdexcept>
class FileOpenException : public std::exception {
public:
const char* what() const throw() {
return "Could not open file.";
}
};
std::ifstream openFile(const std::string& fileName) {
std::ifstream file(fileName);
if (!file) {
throw FileOpenException();
}
return file;
}
int main() {
try {
std::ifstream file = openFile("nonexistent_file.txt");
// ... process the file
} catch (FileOpenException e) {
std::cerr << e.what() << std::endl;
}
return 0;
}What keyword is used to create and throw an exception in C++?
What is the purpose of the `catch` block in C++ exception handling?