C++ error handling

Created By: chatGPT

Error handling is a critical aspect of programming, especially in C++. It allows you to detect and respond to issues that may arise during the execution of a program. In C++, the most common way to handle errors is through the use of exceptions. Exceptions provide a way to react to exceptional circumstances (like runtime errors) in programs by transferring control to special functions known as handlers. This is how you can implement exception handling in C++.
#include <iostream>

void mightGoWrong() {
    bool errorOccurred = true; // Simulate an error condition
    if (errorOccurred) {
        throw std::runtime_error("Something went wrong!");
    }
}

int main() {
    try {
        mightGoWrong();
    } catch (const std::runtime_error& e) {
        std::cerr << "Caught an error: " << e.what() << '\n';
    }
    return 0;
}
In the example above, mightGoWrong is a function that simulates an error condition. If the error occurs, it throws a std::runtime_error exception. The main function contains a try-catch block that calls mightGoWrong and catches the exception if one is thrown. The what method returns the description of the error. This allows the program to handle the error gracefully instead of terminating unexpectedly.
// Custom exception class
class MyException : public std::exception {
public:
    const char* what() const noexcept override {
        return "My custom exception occurred!";
    }
};

void doSomethingRisky() {
    throw MyException();
}

int main() {
    try {
        doSomethingRisky();
    } catch (const MyException& e) {
        std::cerr << "Caught: " << e.what() << '\n';
    }
    return 0;
}
You can also create your own custom exception classes by inheriting from std::exception. In the above code, MyException is a custom class that overrides the what method to provide a specific error message. By doing so, you can categorize and handle different types of errors in a more organized manner. This is particularly useful in larger applications where various modules may throw different exceptions.
void functionThatMightFail() {
    // Simulate an error
    throw std::runtime_error("Failed operation");
}

int main() {
    try {
        functionThatMightFail();
    } catch (const std::runtime_error& e) {
        std::cerr << "Runtime error occurred: " << e.what() << '\n';
    } catch (...) {
        std::cerr << "An unknown error occurred."
    }
    return 0;
}
In addition to specific exception types, you can catch all exceptions by using an ellipsis (catch(...)). This is useful for handling unexpected exceptions that do not match any specific type. However, it's generally advisable to be specific when possible, so you can take appropriate actions based on the type of exception raised.
std::string getValue(bool shouldFail) {
    if (shouldFail) {
        throw std::invalid_argument("Invalid argument provided");
    }
    return "Valid value";
}

int main() {
    try {
        std::string value = getValue(true);
    } catch (const std::invalid_argument& e) {
        std::cerr << "Caught an invalid argument: " << e.what() << '\n';
    }
    return 0;
}
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