๐จ C++ Exception Handling โ Catch & Manage Runtime Errors Gracefully
๐งฒ Introduction โ Why Exception Handling Matters in C++
In modern C++ applications, handling unexpected situationsโlike file errors, memory issues, or invalid user inputsโis essential. Exception handling provides a structured way to manage errors at runtime without crashing the program.
๐ฏ In this guide, youโll learn:
- What C++ exception handling is
- Syntax of
try,throw, andcatch - How to use standard and custom exceptions
- Best practices for robust and maintainable error control
๐ What Is Exception Handling in C++?
Exception handling is a mechanism that allows a program to detect and handle runtime errors dynamically by:
- Throwing an exception
- Catching it using a handler
- Executing a recovery or fallback path
๐ป Code Examples โ With Output
โ Example 1: Basic try-catch Block
#include <iostream>
using namespace std;
int divide(int a, int b) {
if (b == 0)
throw "Division by zero error!";
return a / b;
}
int main() {
try {
cout << divide(10, 0);
} catch (const char* msg) {
cout << "Caught Exception: " << msg << endl;
}
return 0;
}
๐ข Output:
Caught Exception: Division by zero error!
โ Example 2: Using Standard Exception Classes
#include <iostream>
#include <stdexcept>
using namespace std;
int main() {
try {
throw runtime_error("Something went wrong!");
} catch (const runtime_error& e) {
cout << "Runtime Error: " << e.what() << endl;
}
}
๐ข Output:
Runtime Error: Something went wrong!
๐งฑ Syntax of Exception Handling
try {
// Code that might throw
} catch (Type e) {
// Handler
}
โ Throwing Exceptions
throw value; // Can be a primitive, string, or object
throw std::runtime_error("Error");
โ Catching Multiple Types
catch (int e) { /* ... */ }
catch (const char* e) { /* ... */ }
catch (...) { /* Catch-all block */ }
๐ง Custom Exception Classes
You can create your own exceptions by inheriting from std::exception.
class MyException : public std::exception {
public:
const char* what() const noexcept override {
return "Custom exception occurred!";
}
};
๐ Exception Types in Standard Library
| Exception Class | Use Case |
|---|---|
std::exception | Base class for all exceptions |
std::runtime_error | Errors detected during program execution |
std::logic_error | Program logic issues |
std::invalid_argument | Bad function arguments |
std::out_of_range | Out-of-bounds errors |
std::bad_alloc | Memory allocation failure |
๐ก Best Practices & Tips
๐ Best Practice: Always throw objects (not primitive types) when possibleโprefer std::exception derivatives.
๐ก Tip: Catch exceptions by reference (catch (const std::exception& e)), not by value, to avoid slicing.
โ ๏ธ Pitfall: Avoid throwing exceptions in destructorsโit can lead to undefined behavior if another exception is active.
๐ ๏ธ Use Cases for Exception Handling
๐ Secure Code: Prevent access violations or illegal memory operations
๐ File Handling: Handle read/write/open failures
๐ Networking: Detect packet drops, timeouts, and disconnections
๐ Data Processing: Validate user inputs, formats, ranges
๐ก Resource Management: Roll back transactions or free memory on failure
๐ Summary โ Recap & Next Steps
๐ Key Takeaways:
- C++ uses
try,throw, andcatchfor exception handling - Exceptions allow recovery from runtime errors without crashing
- Prefer
std::exceptionhierarchy or custom class exceptions
โ๏ธ Real-World Relevance:
Exception handling is essential for building secure, crash-resistant applications, especially in finance, healthcare, robotics, or system-level code.
โ Next Steps:
- Learn about C++ Signal Handling
- Explore how to manage OS-level signals like interrupts or segmentation faults
โFAQ โ C++ Exception Handling
โCan I throw any data type in C++?
โ
Yes, but it’s best to throw objects (like std::exception) for better structure and information.
โWhat happens if an exception is not caught?
โ ๏ธ The program calls std::terminate() and aborts execution.
โIs catch (...) good practice?
โ
It catches all exceptions but should be used sparingly, ideally for logging or fallback.
โWhatโs the difference between throw and throws?
๐ C++ uses only throw; throws is a Java keyword.
โCan I rethrow an exception?
โ
Yes. Use throw; inside a catch block to rethrow the current exception.
Share Now :
