Master C++ Exception Handling: Practical Try, Catch, Throw Examples
What Is Exception Handling in C++?
Exception handling lets C++ programs gracefully recover from unexpected runtime errors. When an error occurs, control jumps to a special handler that can decide how to respond.
By enclosing potentially problematic code inside a try block and following it with one or more catch clauses, you give the program a clear path to manage exceptional conditions.
If no exception is thrown, the try block runs normally and the handlers are bypassed.
In this tutorial you’ll learn:
- What exception handling is and why it matters
- The core keywords:
throw,catch,try - Syntax and common patterns
- Standard exceptions defined by the C++ Standard Library
- How to create and use user‑defined exceptions
Why Exception Handling?
Exception handling offers several tangible benefits:
- Separates error‑handling logic from regular code, improving readability and maintainability.
- Allows functions to expose only the exceptions they care about; callers can handle the rest.
Key Exception Handling Keywords
Three keywords form the backbone of C++ exception handling:
- throw – signals an error condition by creating an exception object.
- catch – intercepts an exception and provides code to react to it.
- try – marks the region of code that may throw exceptions.
Code inside the try block is called protected code; if it throws, the corresponding catch block is executed.
Syntax
try {
// protected code
} catch (Exception_Name exception1) {
// handle exception1
} catch (Exception_Name exception2) {
// handle exception2
} // ... more catch blocks
- A single
trycan be followed by multiplecatchclauses. - The type in each
catchclause specifies the exception to be caught. - Inside a
catch, the caught exception can be referenced by the chosen identifier.
Example 1: Accessing a Vector Element Out of Range
#include<iostream>
#include<vector>
using namespace std;
int main() {
vector<int> vec;
vec.push_back(0);
vec.push_back(1);
try {
vec.at(2); // out of range
} catch (exception& ex) {
cout << "Exception occurred!" << endl;
}
return 0;
}
Output:

Here is a screenshot of the code:

Code Breakdown:
- Include
iostreamandvectorfor I/O and container support. - Use the
stdnamespace to avoid fully‑qualified names. - Instantiate a
vector<int>and populate it. - Attempt to access an element beyond the vector’s bounds inside a
tryblock. - Catch the standard
std::exceptionand output a message. - Return from
main.
Example 2: Handling Division by Zero
#include <iostream>
using namespace std;
double zeroDivision(int x, int y) {
if (y == 0) {
throw "Division by Zero!";
}
return static_cast(x) / y;
}
int main() {
int a = 11;
int b = 0;
double c = 0;
try {
c = zeroDivision(a, b);
cout << c << endl;
} catch (const char* message) {
cerr << message << endl;
}
return 0;
}
Output:

Here is a screenshot of the code:

Code Breakdown:
- Define
zeroDivisionthat throws a C‑string when dividing by zero. - Call the function inside a
tryblock and print the result. - Catch the string exception and output an error message.
C++ Standard Exceptions

The Standard Library declares a rich hierarchy of exceptions in <exception>. Below are the most frequently used:
new on allocation failure.dynamic_cast when a cast fails.typeid on a glvalue of a polymorphic type that is null.vector::at when index is out of bounds.User‑Defined Exceptions
The std::exception base class can be extended to create domain‑specific error types. Overriding what() provides a descriptive message.
Example: Custom Exception
#include <iostream>
#include <exception>
using namespace std;
class NewException : public exception {
public:
const char* what() const noexcept override {
return "newException occurred";
}
} newex;
int main() {
try {
throw newex;
} catch (exception& ex) {
cout << ex.what() << '\n';
}
return 0;
}
Output:

Here is a screenshot of the code:

Code Breakdown:
- Derive
NewExceptionfromstd::exceptionand overridewhat(). - Instantiate an object
newexto throw. - Throw
newexinside atryblock. - Catch by reference to
std::exceptionand print the message viawhat().
Take‑away
- Exception handling is essential for robust C++ applications that must recover from runtime errors.
- Use
tryto protect code,catchto respond, andthrowto signal problems. - Leverage the rich set of standard exceptions, and extend
std::exceptionwhen custom error types are needed. - Keep error‑handling logic separate from business logic for cleaner, maintainable code.
C Language
- C++ Comments: Best Practices for Readable, Maintainable Code
- C++ For Loops Explained: Syntax, Workflow, and Practical Examples
- Mastering std::stack in C++: A Comprehensive Guide with Practical Examples
- C++ Structs Explained with a Practical Example
- Mastering std::list in C++: Syntax, Functions & Practical Examples
- Master Java Exception Handling: Try‑Catch, Finally, and Class Hierarchy Explained
- Master Python Exception Handling: Using try, except, finally, and raise Effectively
- Mastering C++ Exception Handling: A Comprehensive Guide
- Master C++ Signal Handling: Safe Interrupt Management and Clean Program Termination
- Mastering C# Exception Handling: Strategies & Best Practices