WikiGalaxy

Personalize

C++ Exceptions

Introduction to Exceptions:

Exceptions in C++ are used to handle errors and exceptional situations gracefully without crashing the program. They provide a way to transfer control from one part of a program to another.

Basic Try-Catch Block

Try-Catch Syntax:

A try-catch block is used to handle exceptions. The code that may throw an exception is placed inside the try block, and the catch block handles the exception.


      #include <iostream>
      using namespace std;

      int main() {
        try {
          throw 20;
        } catch (int e) {
          cout << "An exception occurred. Exception Nr. " << e << endl;
        }
        return 0;
      }
    

Console Output:

An exception occurred. Exception Nr. 20

Multiple Catch Blocks

Handling Different Exceptions:

You can have multiple catch blocks to handle different types of exceptions separately.


      #include <iostream>
      using namespace std;

      int main() {
        try {
          throw 'a';
        } catch (int e) {
          cout << "Integer exception caught." << endl;
        } catch (char e) {
          cout << "Character exception caught." << endl;
        }
        return 0;
      }
    

Console Output:

Character exception caught.

Catching All Exceptions

Using Catch-All:

The catch(...) block is used to catch all types of exceptions. It must be the last catch block.


      #include <iostream>
      using namespace std;

      int main() {
        try {
          throw 5.5;
        } catch (...) {
          cout << "Default exception caught." << endl;
        }
        return 0;
      }
    

Console Output:

Default exception caught.

Throwing Exceptions

Explicit Throw:

You can throw an exception explicitly using the throw keyword followed by an exception object or value.


      #include <iostream>
      using namespace std;

      void checkNumber(int num) {
        if (num < 0) {
          throw "Negative number not allowed.";
        }
      }

      int main() {
        try {
          checkNumber(-1);
        } catch (const char* msg) {
          cout << "Exception: " << msg << endl;
        }
        return 0;
      }
    

Console Output:

Exception: Negative number not allowed.

Custom Exception Classes

Creating Custom Exceptions:

You can define your own exception classes by extending the standard exception class.


      #include <iostream>
      #include <exception>
      using namespace std;

      class MyException : public exception {
        public:
          const char* what() const throw() {
            return "My custom exception";
          }
      };

      int main() {
        try {
          throw MyException();
        } catch (MyException& e) {
          cout << e.what() << endl;
        }
        return 0;
      }
    

Console Output:

My custom exception

Rethrowing Exceptions

Rethrow in Catch Block:

You can rethrow an exception from a catch block to be handled further up the call stack.


      #include <iostream>
      using namespace std;

      void function1() {
        try {
          throw 100;
        } catch (int e) {
          cout << "Caught in function1, rethrowing..." << endl;
          throw;
        }
      }

      int main() {
        try {
          function1();
        } catch (int e) {
          cout << "Caught in main: " << e << endl;
        }
        return 0;
      }
    

Console Output:

Caught in function1, rethrowing...

Caught in main: 100

Exception Specifications

Function Exception Specification:

In C++, you can specify the exceptions a function might throw using the noexcept keyword.


      #include <iostream>
      using namespace std;

      void mayThrow() noexcept(false) {
        throw 42;
      }

      int main() {
        try {
          mayThrow();
        } catch (int e) {
          cout << "Caught exception: " << e << endl;
        }
        return 0;
      }
    

Console Output:

Caught exception: 42

Stack Unwinding

Understanding Stack Unwinding:

When an exception is thrown, C++ performs stack unwinding, which involves the destruction of all objects in the scope of the try block.


      #include <iostream>
      using namespace std;

      class Test {
        public:
          ~Test() {
            cout << "Destructor called" << endl;
          }
      };

      int main() {
        try {
          Test t;
          throw 1;
        } catch (int e) {
          cout << "Exception caught" << endl;
        }
        return 0;
      }
    

Console Output:

Destructor called

Exception caught

Standard Exceptions

Using Standard Exceptions:

C++ provides a set of standard exceptions defined in the <exception> header, such as std::out_of_range, std::invalid_argument, etc.


      #include <iostream>
      #include <stdexcept>
      using namespace std;

      int main() {
        try {
          throw out_of_range("Out of range error");
        } catch (out_of_range& e) {
          cout << "Caught: " << e.what() << endl;
        }
        return 0;
      }
    

Console Output:

Caught: Out of range error

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025