C++ try block

Created By: chatGPT

C++ provides a mechanism for handling exceptions through try and catch blocks. The try block allows you to write code that might throw an exception, while the catch block lets you handle that exception gracefully. Using these constructs can make your program more robust and prevent it from crashing unexpectedly due to errors. Here’s how you can implement a try block in C++.
#include <iostream>

int main() {
    try {
        int num1 = 10;
        int num2 = 0;
        if (num2 == 0) {
            throw std::runtime_error("Division by zero");
        }
        int result = num1 / num2;
        std::cout << "Result: " << result << std::endl;
    } catch (const std::runtime_error& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }
    return 0;
}
In this example, we attempt to perform a division operation. Since division by zero is not allowed, we throw a runtime_error with a relevant message. The catch block then catches this exception and prints an error message to the standard error stream. This way, the program can continue executing without crashing.
// Output if num2 is 0:
// Error: Division by zero
Exceptions can also be thrown for other reasons, such as invalid input or exceeding array bounds. It's crucial to anticipate potential errors and handle them appropriately within your try and catch blocks. This leads to more maintainable and user-friendly applications.
std::vector<int> vec{1, 2, 3};
try {
    if (vec.size() < 5) {
        throw std::out_of_range("Index out of range");
    }
} catch (const std::out_of_range& e) {
    std::cerr << "Error: " << e.what() << std::endl;
}
Introduction And SetupVariablesData TypesIntFloatDoubleCharBoolStringVoidConstantsOperatorsArithmetic OperatorsRelational OperatorsLogical OperatorsBitwise OperatorsAssignment OperatorsTernary OperatorControl FlowIf StatementElse StatementElse If StatementSwitch StatementFor LoopWhile LoopDo While LoopBreak StatementContinue StatementGoto StatementFunctionsFunction DeclarationFunction DefinitionFunction OverloadingInline FunctionsDefault ArgumentsRecursionPass By ValuePass By ReferenceData StructuresArraysMultidimensional ArraysStructsEnumsUnionsClassesObjectsMember FunctionsConstructorsDestructorsAccess SpecifiersPublicPrivateProtectedInheritancePolymorphismFunction OverridingVirtual FunctionsPure Virtual FunctionsOperator OverloadingTemplatesNamespaceCommentsSingle Line CommentsMulti Line CommentsSyntaxSemicolonCurly BracesParenthesesEvent HandlingCinCoutError HandlingTry BlockCatch BlockThrow StatementException HandlingPreprocessor DirectivesInclude GuardsMacro DefinitionsInline AssemblyStatic KeywordsExtern KeywordsConst KeywordsVolatile KeywordsFriend FunctionStatic MemberThis PointerDynamic Memory AllocationNew OperatorDelete Operator