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 :
This is thrown when a too big std::string is created. This can be thrown by the 'at' method, for example a std::vector and std::bitset<>::operator[](). An exception that theoretically cannot be detected by reading the code.
C doesn't support exceptions. You can try compiling your C code as C++ with Visual Studio or G++ and see if it'll compile as-is. Most C applications will compile as C++ without major changes, and you can then use the try... catch syntax.
You need to catch it with char const* instead of char* . Neither anything like std::string nor char* will catch it. Catching has restricted rules with regard to what types it match.
Throwing an exception is as simple as using the "throw" statement. You then specify the Exception object you wish to throw. Every Exception includes a message which is a human-readable error description. It can often be related to problems with user input, server, backend, etc.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With