简体   繁体   English

C++ 异常 - 抛出一个字符串

[英]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.出于某种原因,当我尝试使用下面的代码抛出一个字符串时,我在 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!随意定义一个自定义异常类,并在其中嵌入一个字符串(或者只是从std::runtime_error派生自定义异常类,将错误消息传递给构造函数,并使用what()方法获取错误字符串捕捉现场的),但抛出一个字符串!

you are currently throwing a const char* and not a std::string , instead you should be throwing string("error")您当前抛出的是const char*而不是std::string ,而是应该抛出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';
    }
}'''

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM