cpp
examples
examples.cpp⚙️cpp
/**
* Exception Handling - Examples
* Compile: g++ -std=c++17 -Wall examples.cpp -o examples
*/
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
#include <memory>
using namespace std;
// ============================================================
// SECTION 1: BASIC TRY-CATCH
// ============================================================
void demoBasic() {
cout << "--- Basic try-catch ---\n" << endl;
try {
cout << " Throwing runtime_error..." << endl;
throw runtime_error("Something went wrong!");
}
catch (const runtime_error& e) {
cout << " Caught: " << e.what() << endl;
}
cout << " Execution continues after catch" << endl;
}
// ============================================================
// SECTION 2: MULTIPLE CATCH BLOCKS
// ============================================================
void riskyOperation(int code) {
switch (code) {
case 1: throw invalid_argument("Invalid argument");
case 2: throw out_of_range("Out of range");
case 3: throw runtime_error("Runtime error");
case 4: throw 42; // Non-standard throw
}
}
void demoMultipleCatch() {
cout << "\n--- Multiple Catch Blocks ---\n" << endl;
for (int i = 1; i <= 5; i++) {
try {
riskyOperation(i);
}
catch (const invalid_argument& e) {
cout << " Code " << i << ": invalid_argument - " << e.what() << endl;
}
catch (const out_of_range& e) {
cout << " Code " << i << ": out_of_range - " << e.what() << endl;
}
catch (const exception& e) {
cout << " Code " << i << ": exception - " << e.what() << endl;
}
catch (...) {
cout << " Code " << i << ": unknown exception" << endl;
}
}
}
// ============================================================
// SECTION 3: THROWING EXCEPTIONS
// ============================================================
int divide(int a, int b) {
if (b == 0) {
throw invalid_argument("Division by zero");
}
return a / b;
}
double squareRoot(double x) {
if (x < 0) {
throw domain_error("Cannot compute sqrt of negative number");
}
return sqrt(x);
}
void demoThrowing() {
cout << "\n--- Throwing Exceptions ---\n" << endl;
try {
cout << " 10 / 2 = " << divide(10, 2) << endl;
cout << " 10 / 0 = " << divide(10, 0) << endl;
}
catch (const exception& e) {
cout << " Error: " << e.what() << endl;
}
try {
cout << " sqrt(16) = " << squareRoot(16) << endl;
cout << " sqrt(-4) = " << squareRoot(-4) << endl;
}
catch (const exception& e) {
cout << " Error: " << e.what() << endl;
}
}
// ============================================================
// SECTION 4: STANDARD EXCEPTIONS
// ============================================================
void demoStandardExceptions() {
cout << "\n--- Standard Exceptions ---\n" << endl;
// out_of_range
try {
vector<int> v = {1, 2, 3};
cout << " v.at(10) = " << v.at(10) << endl;
}
catch (const out_of_range& e) {
cout << " out_of_range: " << e.what() << endl;
}
// invalid_argument (from stoi)
try {
int n = stoi("not_a_number");
cout << " Parsed: " << n << endl;
}
catch (const invalid_argument& e) {
cout << " invalid_argument: " << e.what() << endl;
}
// length_error
try {
string s;
s.resize(s.max_size() + 1);
}
catch (const length_error& e) {
cout << " length_error: " << e.what() << endl;
}
}
// ============================================================
// SECTION 5: CUSTOM EXCEPTION
// ============================================================
class FileNotFoundException : public runtime_error {
string filename;
public:
FileNotFoundException(const string& fname)
: runtime_error("File not found: " + fname), filename(fname) {}
const string& getFilename() const { return filename; }
};
class ValidationException : public exception {
string field;
string message;
public:
ValidationException(const string& f, const string& msg)
: field(f), message(msg) {}
const char* what() const noexcept override {
return message.c_str();
}
const string& getField() const { return field; }
};
void demoCustomException() {
cout << "\n--- Custom Exceptions ---\n" << endl;
try {
throw FileNotFoundException("config.json");
}
catch (const FileNotFoundException& e) {
cout << " FileNotFoundException: " << e.what() << endl;
cout << " File: " << e.getFilename() << endl;
}
try {
throw ValidationException("email", "Invalid email format");
}
catch (const ValidationException& e) {
cout << " ValidationException in '" << e.getField()
<< "': " << e.what() << endl;
}
}
// ============================================================
// SECTION 6: RETHROWING
// ============================================================
void innerFunction() {
throw runtime_error("Error in inner function");
}
void middleFunction() {
try {
innerFunction();
}
catch (const exception& e) {
cout << " Middle caught and rethrowing: " << e.what() << endl;
throw; // Rethrow
}
}
void demoRethrow() {
cout << "\n--- Rethrowing Exceptions ---\n" << endl;
try {
middleFunction();
}
catch (const exception& e) {
cout << " Outer caught: " << e.what() << endl;
}
}
// ============================================================
// SECTION 7: NOEXCEPT
// ============================================================
void safeFunction() noexcept {
// Guaranteed not to throw
cout << " Safe function executed" << endl;
}
void mayThrow() {
throw runtime_error("I throw!");
}
void demoNoexcept() {
cout << "\n--- noexcept ---\n" << endl;
cout << " safeFunction noexcept: " << boolalpha
<< noexcept(safeFunction()) << endl;
cout << " mayThrow noexcept: "
<< noexcept(mayThrow()) << endl;
safeFunction();
}
// ============================================================
// SECTION 8: EXCEPTION-SAFE RAII
// ============================================================
class Resource {
string name;
public:
Resource(const string& n) : name(n) {
cout << " Resource acquired: " << name << endl;
}
~Resource() {
cout << " Resource released: " << name << endl;
}
};
void demoRAII() {
cout << "\n--- Exception-Safe RAII ---\n" << endl;
try {
Resource r1("Database Connection");
Resource r2("File Handle");
cout << " Throwing exception..." << endl;
throw runtime_error("Simulated error");
// Resources are automatically cleaned up
}
catch (const exception& e) {
cout << " Caught: " << e.what() << endl;
}
cout << " Resources were properly released!" << endl;
}
// ============================================================
// MAIN
// ============================================================
int main() {
cout << "╔══════════════════════════════════════╗" << endl;
cout << "║ EXCEPTION HANDLING - EXAMPLES ║" << endl;
cout << "╚══════════════════════════════════════╝" << endl;
demoBasic();
demoMultipleCatch();
demoThrowing();
demoStandardExceptions();
demoCustomException();
demoRethrow();
demoNoexcept();
demoRAII();
cout << "\n=== Complete ===" << endl;
return 0;
}