⚙️ C++ Beginner

What is exception handling in C++?

Answer

C++ exception handling provides a mechanism to handle runtime errors gracefully — separating error-handling code from normal logic. Mechanism: try { // Code that might throw int* arr = new int[1000000000]; // Might fail if (arr == nullptr) throw std::bad_alloc(); processFile("data.txt"); // Might throw std::ios_base::failure if (age < 0) throw std::invalid_argument("Age can't be negative"); } catch (const std::invalid_argument& e) { std::cerr << "Invalid argument: " << e.what() << "\n"; } catch (const std::bad_alloc& e) { std::cerr << "Out of memory: " << e.what() << "\n"; } catch (const std::exception& e) { std::cerr << "Standard exception: " << e.what() << "\n"; } catch (...) { std::cerr << "Unknown exception!\n"; }. Exception hierarchy: std::exception is the base. Key subclasses: std::runtime_error (logic_error, overflow_error), std::bad_alloc, std::bad_cast, std::ios_base::failure. Catch by const reference to avoid slicing. Custom exceptions: class DatabaseError : public std::runtime_error { public: DatabaseError(const std::string& msg) : std::runtime_error("DB Error: " + msg) {} }; throw DatabaseError("Connection failed");. noexcept (C++11): declare a function won't throw: double sqrt(double x) noexcept;. Allows compiler optimizations; terminates if exception is thrown from noexcept function. Exception safety guarantees: No-throw (never throws — strongest); Strong (commit or rollback — exception leaves no observable state change); Basic (no leaks but state may change); No guarantee (weakest). Prefer designing functions with strong or at least basic guarantees.