#Don't know how to use exception

10 messages · Page 1 of 1 (latest)

tired pelicanBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

viscid rampart
#

You're new to programming and are writing a calculator? That's not a good idea.

queen comet
#

so, in cpp, exception handling generally involves three keywords, try, catch, and throw

#

try encloses the code that you want to execute. if any issue arises inside the try block, an exception is thrown.
throw throws an exception when an issue is encountered. this can be a data type, variable, or object.
catch catches the thrown exception and handles it

#

your code already has some try and catch blocks, you use them to validate the first and second numbers in the expression and check whether they're of the same type (roman or arabic)

#

let's say you want to catch a division by zero error for arabic numbers. you can do this by including another try and catch block around the division part of your code:

#
// Existing code...
else // The else block corresponding to the Arabic calculation
{
    if (stroper == "+")
    {
        return number1 + number2 - 500;
    }
    else if (stroper == "-")
    {
        return number1 - number2 - 500;
    }
    else if (stroper == "*")
    {
        return number1 * number2 - 500;
    }
    else if (stroper == "/")
    {
        try
        {
            if (number2 == 0)
            {
                throw "Division by zero"; // Throwing a string exception here
            }
            return number1 / number2 - 500;
        }
        catch (const char* e) // Catching a string exception
        {
            cout << "Error: " << e << endl;
            exit(0);
        }
    }
}
#

here, if number2 is zero, an exception with the message "Division by zero" is thrown. the corresponding catch block catches this exception and prints out an error message before exiting the program

#

you can do similar things to introduce additional exceptions to handle other edge cases or errors in your program

#

hope that helps