C++ try catch
C++ try catch with Explanations
#include <iostream>
int main() {
try {
int a = 10;
int b = 0;
if (b == 0) {
throw "Division by zero error";
}
int result = a / b;
std::cout << "Result: " << result << std::endl;
}
catch (const char* message) {
std::cout << "Exception caught: " << message << std::endl;
}
return 0;
}
- Explanation:
- The
try
block is used to enclose the code that may throw an exception. - Inside the
try
block, two integer variablesa
andb
are declared with values 10 and 0, respectively. - An
if
statement checks ifb
is equal to 0, and if true, it throws a string "Division by zero error" using thethrow
keyword. - If no exception is thrown, the result of the division
a / b
is calculated and printed to the console. - The
catch
block is used to handle the exception. It catches an exception of typeconst char*
(a string) and prints the message to the console.
This program demonstrates the use of try
and catch
blocks in C++ to handle exceptions that may occur during the execution of the code within the try
block. If an exception is thrown, the program jumps to the corresponding catch
block to handle the exception.