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 :
Throwing a string is really a bad idea.
Feel free to define a custom exception class, and have a string embedded inside (or just derive your custom exception class from std::runtime_error
, pass an error message to the constructor, and use the what()
method to get the error string at the catch-site), but do not throw a string!
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");
'''#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 std::runtime_error("Exception ! Error");
}
}
catch(const std::exception& e)
{
std::cout << "Caught exception: " << e.what() << '\n';
}
}'''
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.