C++ Exceptions
β οΈ C++ Exceptions (Exception Handling)
Exceptions in C++ are used to handle runtime errors gracefully without crashing the program.
They separate error-handling code from normal program logic.
πΉ 1. Why Use Exceptions?
Handle unexpected runtime errors
Prevent program crashes
Improve readability and maintainability
Provide centralized error handling
πΉ 2. Basic Exception Handling Syntax
C++ uses three keywords:
πΉ 3. Simple Example
πΉ 4. Catching Different Types of Exceptions
β catch(...) catches all exceptions
πΉ 5. Using Standard Exceptions (<exception>)
πΉ 6. Multiple catch Blocks
πΉ 7. Throwing Exceptions from Functions
πΉ 8. Re-throwing an Exception
πΉ 9. Custom Exception Class
Usage:
πΉ 10. Stack Unwinding (Important Concept)
When an exception is thrown:
Function calls are unwound
Local objects are destroyed
Control jumps to nearest
catch
πΉ 11. noexcept Keyword
β Improves performance
β Used in destructors
πΉ 12. Exceptions vs Error Codes
| Exceptions | Error Codes |
|---|---|
| Cleaner code | Cluttered code |
| Central handling | Manual checks |
| Slight overhead | Faster |
β Common Mistakes
β Correct:
π Summary
Exceptions handle runtime errors safely
Use
try,throw,catchCatch by reference
Use standard exceptions when possible
Avoid exceptions for normal flow control
