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:
Header inclusion: The
<iostream>
header is included to enable input and output operations.mightGoWrong()
function: A function is defined without any parameters and return typevoid
. Inside this function:- Two boolean variables
error1
anderror2
are declared and initialized. - Two conditional blocks check the values of these boolean variables.
- If
error1
istrue
, a C-style string exception"Error 1 occurred."
is thrown usingthrow
. - If
error2
istrue
, astd::string
exception"Error 2 occurred."
is thrown usingthrow
.
- Two boolean variables
main()
function: The program's entry point where execution begins.- Inside a
try
block, themightGoWrong()
function is called. Two
catch
blocks follow to handle exceptions that might occur in thetry
block:- The first
catch
block catches exceptions of typeconst char*
and prints the corresponding error message. - The second
catch
block catches exceptions of typestd::string
and prints the corresponding error message.
- The first
After exception handling, a message
"Program still running."
is printed to indicate that the program has continued executing despite the exceptions.
- Inside a
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.