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:

try {
// code that may cause error
}
catch (exception_type) {
// code to handle error
}

πŸ”Ή 3. Simple Example

#include <iostream>
using namespace std;

int main() {
try {
int a = 10, b = 0;
if (b == 0)
throw "Division by zero";

cout << a / b;
}
catch (const char* msg) {
cout << "Error: " << msg;
}
}


πŸ”Ή 4. Catching Different Types of Exceptions

try {
throw 10;
}
catch (int e) {
cout << "Integer exception: " << e;
}
catch (...) {
cout << "Unknown exception";
}

βœ” catch(...) catches all exceptions


πŸ”Ή 5. Using Standard Exceptions (<exception>)

#include <exception>

try {
throw std::runtime_error("File not found");
}
catch (const std::exception& e) {
cout << e.what();
}


πŸ”Ή 6. Multiple catch Blocks

try {
int x = -1;
if (x < 0)
throw x;
}
catch (int e) {
cout << "Negative value";
}
catch (...) {
cout << "Other error";
}

πŸ”Ή 7. Throwing Exceptions from Functions

int divide(int a, int b) {
if (b == 0)
throw std::invalid_argument("Divide by zero");
return a / b;
}

πŸ”Ή 8. Re-throwing an Exception

try {
try {
throw "Error occurred";
}
catch (...) {
cout << "Handling and rethrowing\n";
throw;
}
}
catch (...) {
cout << "Caught again";
}

πŸ”Ή 9. Custom Exception Class

class MyException : public exception {
public:
const char* what() const noexcept {
return "Custom Exception";
}
};

Usage:

throw MyException();

πŸ”Ή 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

void func() noexcept {
// guaranteed not to throw
}

βœ” Improves performance
βœ” Used in destructors


πŸ”Ή 12. Exceptions vs Error Codes

ExceptionsError Codes
Cleaner codeCluttered code
Central handlingManual checks
Slight overheadFaster

❌ Common Mistakes

catch (exception e) // ❌ slicing

βœ” Correct:

catch (const exception& e)

πŸ“Œ Summary

  • Exceptions handle runtime errors safely

  • Use try, throw, catch

  • Catch by reference

  • Use standard exceptions when possible

  • Avoid exceptions for normal flow control

You may also like...