C++ Exception - Throw a String

ID : 274508

viewed : 36

Tags : c++exceptionerror-handlingc++

Top 4 Answer for C++ Exception - Throw a String

vote vote


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!

vote vote


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"); 
vote vote


#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';     } } 
vote vote


Top 3 video Explaining C++ Exception - Throw a String