【问题标题】:String throwing exception字符串抛出异常
【发布时间】:2022-01-17 14:50:29
【问题描述】:

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

#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

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

【问题讨论】:

  • 代码具体有什么问题?你有什么意见?请注意,您正在捕获const char*,但您正在抛出std::string。我不确定这是否应该工作。
  • 你正在抛出一个std::string,但你试图抓住一个const char*
  • @SimonKraemer,@churill,是的,我确实想过,但我不知道字符串的走动,因为string exception 不正确
  • P x; T(x); 将一个不同的x 传递给T,而不是你用std::cin 初始化的那个。在 T 中,您以 b.first==0 开头,但 first 成员未初始化,这意味着它具有未定义的行为。
  • 下一个问题std::cin &gt;&gt; x; 将在第一个空白处停止读取。您需要使用std::getline 来阅读整行。我还建议学习如何使用调试器来调查程序在运行时的状态。

标签: c++ exception constructor


【解决方案1】:

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

话虽如此,您的代码中有很多不一致之处。

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

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

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

第一个try 块调用UB,因为您在该块中声明了一个 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;
}

【讨论】:

  • 感谢您的完整评论,getline 的评论非常有帮助!我想这就是我一直在寻找的问题
猜你喜欢
  • 1970-01-01
  • 2015-01-26
  • 1970-01-01
  • 2016-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多