Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> C Language

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:

Why Exception Handling?

Exception handling offers several tangible benefits:

Key Exception Handling Keywords

Three keywords form the backbone of C++ exception handling:

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

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:

Master C++ Exception Handling: Practical Try, Catch, Throw Examples

Here is a screenshot of the code:

Master C++ Exception Handling: Practical Try, Catch, Throw Examples

Code Breakdown:

  1. Include iostream and vector for I/O and container support.
  2. Use the std namespace to avoid fully‑qualified names.
  3. Instantiate a vector<int> and populate it.
  4. Attempt to access an element beyond the vector’s bounds inside a try block.
  5. Catch the standard std::exception and output a message.
  6. 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:

Master C++ Exception Handling: Practical Try, Catch, Throw Examples

Here is a screenshot of the code:

Master C++ Exception Handling: Practical Try, Catch, Throw Examples

Code Breakdown:

  1. Define zeroDivision that throws a C‑string when dividing by zero.
  2. Call the function inside a try block and print the result.
  3. Catch the string exception and output an error message.

C++ Standard Exceptions

Master C++ Exception Handling: Practical Try, Catch, Throw Examples

The Standard Library declares a rich hierarchy of exceptions in <exception>. Below are the most frequently used:

ExceptionDescription std::exceptionBase class for all standard exceptions. std::bad_allocThrown by new on allocation failure. std::bad_castThrown by dynamic_cast when a cast fails. std::bad_exceptionUsed to signal an unexpected exception. std::bad_typeidThrown by typeid on a glvalue of a polymorphic type that is null. std::logic_errorErrors that should be detectable by the programmer. std::domain_errorInvalid domain for a mathematical function. std::invalid_argumentFunction received an invalid argument. std::length_errorAttempt to create a string that is too large. std::out_of_rangeThrown by vector::at when index is out of bounds. std::runtime_errorRuntime errors that are not caught by other categories. std::overflow_errorMathematical overflow occurred. std::range_errorValue is out of range for the operation. std::underflow_errorMathematical underflow occurred.

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:

Master C++ Exception Handling: Practical Try, Catch, Throw Examples

Here is a screenshot of the code:

Master C++ Exception Handling: Practical Try, Catch, Throw Examples

Code Breakdown:

  1. Derive NewException from std::exception and override what().
  2. Instantiate an object newex to throw.
  3. Throw newex inside a try block.
  4. Catch by reference to std::exception and print the message via what().

Take‑away

C Language

  1. C++ Comments: Best Practices for Readable, Maintainable Code
  2. C++ For Loops Explained: Syntax, Workflow, and Practical Examples
  3. Mastering std::stack in C++: A Comprehensive Guide with Practical Examples
  4. C++ Structs Explained with a Practical Example
  5. Mastering std::list in C++: Syntax, Functions & Practical Examples
  6. Master Java Exception Handling: Try‑Catch, Finally, and Class Hierarchy Explained
  7. Master Python Exception Handling: Using try, except, finally, and raise Effectively
  8. Mastering C++ Exception Handling: A Comprehensive Guide
  9. Master C++ Signal Handling: Safe Interrupt Management and Clean Program Termination
  10. Mastering C# Exception Handling: Strategies & Best Practices