c++ catch Unhandled exception

#include <iostream>

void mightGoWrong() {
    bool error1 = false;
    bool error2 = true;

    if (error1) {
        throw "Error 1 occurred.";
    }

    if (error2) {
        throw std::string("Error 2 occurred.");
    }
}

int main() {
    try {
        mightGoWrong();
    } catch (const char* errorMsg) {
        std::cout << "Caught exception: " << errorMsg << std::endl;
    } catch (std::string errorMsg) {
        std::cout << "Caught exception: " << errorMsg << std::endl;
    }

    std::cout << "Program still running." << std::endl;

    return 0;
}

Explanation:

  1. Header inclusion: The <iostream> header is included to enable input and output operations.

  2. mightGoWrong() function: A function is defined without any parameters and return type void. Inside this function:

    • Two boolean variables error1 and error2 are declared and initialized.
    • Two conditional blocks check the values of these boolean variables.
    • If error1 is true, a C-style string exception "Error 1 occurred." is thrown using throw.
    • If error2 is true, a std::string exception "Error 2 occurred." is thrown using throw.
  3. main() function: The program's entry point where execution begins.

    • Inside a try block, the mightGoWrong() function is called.
    • Two catch blocks follow to handle exceptions that might occur in the try block:

      • The first catch block catches exceptions of type const char* and prints the corresponding error message.
      • The second catch block catches exceptions of type std::string and prints the corresponding error message.
    • After exception handling, a message "Program still running." is printed to indicate that the program has continued executing despite the exceptions.

  4. Return: The main() function returns 0 to indicate successful program execution.

This code demonstrates the use of try, throw, and catch for exception handling in C++. The try block contains code that might throw exceptions, and catch blocks handle those exceptions, allowing the program to manage errors gracefully.