字符串抛出异常

String throwing exception

我有以下代码,其中包含两个函数,当满足条件时应该抛出异常。不幸的是,第二个带字符串的似乎不起作用,我不知道出了什么问题

#include "iostream"
#include "stdafx.h"
#include "string"
using namespace std;
 
struct P
{
    int first;
    string second;
};
 
void T(P b)
{ if (b.first==0)
throw (b.first);
};
 
void U(P b)
{ if (b.second == "1, 2, 3, 4, 5, 6, 7, 8, 9" )
throw (b.second);
};
 
int _tmain(int argc, _TCHAR* argv[])
{
P x;
cin>>x.first;
cin>>x.second;
 
try
    {  
        P x;
        T(x);
    }
    catch (int exception)
    {
        std::cout << exception;
    }
 
    try{
        U(x);
    }
    catch (const char* exception)
    {
        std::cout << "\n" << exception;
    }
 
system("pause");
return 0;
}

我有以下输入:

0
1, 2, 3, 4, 5, 6, 7, 8, 9

和输出:

0

我想得到:

0
1, 2, 3, 4, 5, 6, 7, 8, 9

如何更改字符串输出的字符?

我不知道你在尝试什么,但尽管语言允许,但应该避免抛出不是 std::exception(的子类)实例的对象。

也就是说你的代码中有很多不一致之处。

第一个 cin >> x.second; 将在 第一个空白字符 处停止。因此,在您的示例中,x.second 中只有 "1,",因此您测试失败并且您的代码不会抛出任何内容。

您应该忽略 cin >> x.first 留下的换行符并使用 getline 阅读整行包含空格:

P x;
cin >> x.first;
cin.ignore();
std::getline(cin, x.second);

第一个 try 块调用 UB,因为您在该块中声明了一个 new x,它将隐藏您刚刚阅读的那个。应该是:

try
{
    //P x;  // do not hide x from the enclosing function!
    T(x);
}

最后,即使这不是错误,您也应该始终通过 const 引用捕获非平凡对象以避免复制。请记住,在异常情况下会引发异常,当内存不足时,您应该避免复制。但是您必须 捕获与抛出的完全相同的对象。所以第二个 catch 应该是:

catch (std::string exception)
{
    std::cout << "\n" << exception;
}

或更好(避免复制):

catch (const std::string& exception)
{
    std::cout << "\n" << exception;
}