C++ Tutorial

Class and Object

Reference

Inheritance and Derivation

Polymorphism and Virtual Functions

Operator Overloading

Template

Exception

Object Oriented Advanced

Input/Output Stream

File Operations

Exception Handling (try catch) in C++

Exception handling in C++ allows you to manage unexpected situations or errors that may occur during program execution. It provides a clean and structured approach to handling errors and improves code maintainability.

In this tutorial, we'll cover the basics of exception handling in C++, including the use of try, catch, and throw.

  • Basic Structure of Exception Handling: Exception handling in C++ is built around three keywords: try, catch, and throw.
  • try: Defines a block of code where an exception might occur.
  • catch: Defines a block of code that will be executed if an exception is thrown within the corresponding try block.
  • throw: Throws an exception that can be caught and handled by a catch block.

Example:

#include <iostream>

int main() {
    try {
        // Code that might throw an exception
        int a = 10, b = 0;
        if (b == 0) {
            throw "Division by zero!";
        }
        int c = a / b;
        std::cout << "Result: " << c << std::endl;
    }
    catch (const char* e) {
        // Code that will be executed if an exception is thrown
        std::cout << "Caught exception: " << e << std::endl;
    }

    return 0;
}

Output:

Caught exception: Division by zero!
  • Catching Different Exception Types: You can catch different types of exceptions by using multiple catch blocks. The appropriate catch block will be executed based on the type of exception thrown.

Example:

#include <iostream>
#include <stdexcept>

int main() {
    try {
        int choice;
        std::cout << "Enter 1 for integer division, 2 for floating-point division: ";
        std::cin >> choice;

        if (choice == 1) {
            int a = 10, b = 0;
            if (b == 0) {
                throw std::runtime_error("Integer division by zero!");
            }
            int c = a / b;
            std::cout << "Result: " << c << std::endl;
        } else if (choice == 2) {
            float a = 10.0f, b = 0.0f;
            if (b == 0) {
                throw "Floating-point division by zero!";
            }
            float c = a / b;
            std::cout << "Result: " << c << std::endl;
        } else {
            throw std::invalid_argument("Invalid choice!");
        }
    }
    catch (const std::runtime_error& e) {
        std::cout << "Caught runtime_error: " << e.what() << std::endl;
    }
    catch (const std::invalid_argument& e) {
        std::cout << "Caught invalid_argument: " << e.what() << std::endl;
    }
    catch (const char* e) {
        std::cout << "Caught exception: " << e << std::endl;
    }

    return 0;
}
  1. How to use try-catch blocks in C++:

    • Description: Introduces the basic structure of try-catch blocks in C++, demonstrating how to catch and handle exceptions.
    • Example Code:
      #include <iostream>
      
      int main() {
          try {
              // Code that may throw an exception
              throw std::runtime_error("An error occurred");
          } catch (const std::exception& e) {
              // Handling the exception
              std::cerr << "Caught exception: " << e.what() << std::endl;
          }
          return 0;
      }
      
  2. Custom exception handling in C++:

    • Description: Demonstrates how to create and handle custom exceptions by defining and throwing user-defined exception classes.
    • Example Code:
      #include <iostream>
      #include <stdexcept>
      
      class CustomException : public std::exception {
      public:
          const char* what() const noexcept override {
              return "Custom exception: Something went wrong.";
          }
      };
      
      int main() {
          try {
              throw CustomException(); // Throwing a custom exception
          } catch (const std::exception& e) {
              std::cerr << "Caught exception: " << e.what() << std::endl;
          }
          return 0;
      }
      
  3. Nested try-catch blocks in C++:

    • Description: Shows how to nest try-catch blocks to handle exceptions at different levels of code, providing finer-grained exception handling.
    • Example Code:
      #include <iostream>
      
      int main() {
          try {
              try {
                  // Nested code that may throw an exception
                  throw std::runtime_error("An error occurred");
              } catch (const std::exception& innerException) {
                  // Handling the inner exception
                  std::cerr << "Inner exception: " << innerException.what() << std::endl;
                  throw; // Rethrowing the exception
              }
          } catch (const std::exception& outerException) {
              // Handling the outer exception
              std::cerr << "Outer exception: " << outerException.what() << std::endl;
          }
          return 0;
      }
      
  4. Handling multiple exceptions in C++:

    • Description: Demonstrates how to handle multiple types of exceptions using multiple catch blocks, allowing different handlers for different exception types.
    • Example Code:
      #include <iostream>
      
      int main() {
          try {
              // Code that may throw an exception
              throw std::runtime_error("An error occurred");
          } catch (const std::runtime_error& runtimeError) {
              // Handling a specific exception type
              std::cerr << "Caught runtime error: " << runtimeError.what() << std::endl;
          } catch (const std::exception& genericException) {
              // Handling a generic exception
              std::cerr << "Caught exception: " << genericException.what() << std::endl;
          }
          return 0;
      }
      
  5. Using noexcept in C++ exception handling:

    • Description: Introduces the noexcept specifier, indicating that a function does not throw exceptions, contributing to improved performance and predictability.
    • Example Code:
      #include <iostream>
      
      void myFunction() noexcept {
          // Code that does not throw exceptions
      }
      
      int main() {
          try {
              myFunction(); // Calling a noexcept function
          } catch (const std::exception& e) {
              // This block will not catch exceptions from myFunction()
              std::cerr << "Caught exception: " << e.what() << std::endl;
          }
          return 0;
      }