Search code examples
c++exceptionerror-handling

C++ Exception - Throw a String


I'm having a small issue with my code. For some reason, when I try to throw a string with the code below, I get an error in Visual Studio.

#include <string>
#include <iostream>
using namespace std;

int main()
{
    
    char input;

    cout << "\n\nWould you like to input? (y/n): ";
    cin >> input;
    input = tolower(input);

    try
    {
        if (input != 'y')
        {
            throw ("exception ! error");
        }
    }
    catch (string e)
    {
        cout << e << endl;
    }
}

Error :

error


Solution

  • You are currently throwing a const char* and not a std::string, instead you should be throwing string("error")

    edit: the error is resolved with

    throw string("exception ! error");