π¨ 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 :
