C++ Exception Handling Tutorial
Exception handling in C++ provides a mechanism to detect and manage runtime errors, ensuring program stability and reliability. It uses the `try`, `catch`, and `throw` keywords to handle exceptions gracefully.
Basic Syntax
Exception handling in C++ involves three main components:
- try: Defines a block of code that might throw an exception.
- catch: Handles the exception thrown by the `try` block.
- throw: Throws an exception to be caught.
#include <iostream>
using namespace std;
int main() {
try {
throw "An error occurred!";
} catch (const char* msg) {
cout << "Caught exception: " << msg << endl;
}
return 0;
}
Handling Multiple Exceptions
Multiple `catch` blocks can handle different exception types:
#include <iostream>
using namespace std;
int main() {
try {
throw 404;
} catch (int e) {
cout << "Caught integer exception: " << e << endl;
} catch (...) {
cout << "Caught unknown exception!" << endl;
}
return 0;
}
Custom Exception Classes
You can create your own exception classes to handle specific scenarios:
#include <iostream>
#include <stdexcept>
using namespace std;
class CustomException : public exception {
public:
const char* what() const noexcept override {
return "Custom exception occurred!";
}
};
int main() {
try {
throw CustomException();
} catch (const CustomException& e) {
cout << e.what() << endl;
}
return 0;
}
Best Practices
- Use exceptions for exceptional conditions, not for regular control flow.
- Catch exceptions by reference to avoid unnecessary copying.
- Always clean up resources using RAII or `try-finally` mechanisms.
×