Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 273
Jimmy Avatar asked Nov 27 '14 21:11

Jimmy


People also ask

Can we throw a string in C++?

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.

Can you throw exceptions in C?

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.

How do you catch a string in C++?

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.

How do you throw an exception?

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.


Video Answer


2 Answers

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!

like image 103
Mr.C64 Avatar answered Oct 09 '22 12:10

Mr.C64


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");
like image 37
Syntactic Fructose Avatar answered Oct 09 '22 12:10

Syntactic Fructose