C++ Exception - Throw a String

ID : 274508

viewed : 36

Tags : c++exceptionerror-handlingc++





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

vote vote

99

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

85

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

73

#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

67

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







Related QUESTION?