【发布时间】:2015-04-22 03:17:20
【问题描述】:
我需要在我的主程序中添加一个或多个 try 块和随附的 catch 处理程序。 catch 处理程序将捕获我的类的重载提取运算符引发的异常。
我实现了重载的提取运算符来抛出一个新的异常,但是我的主程序中的 catch 块似乎没有工作/捕获这些异常。
这是我的主程序中的代码示例。
cout << "\nEnter 2 Complex numbers in the form \"(real_value,imaginary_value)\" :\n";
try
{
cin >> A >> B;
}
catch (Invalid_Mode1_Complex_Value_Exception& exception)
{
cout << "Exception occured: " << exception.what() << endl;
newFormat = cin.flags(); //find out how flags are set now
cout << "\nThe cin format flags are set to: " << newFormat << endl;
exit(1);
}
我做错了什么吗?任何建议或帮助将不胜感激。谢谢。这是引发异常的代码。
// overloads the binary ">>" operator through a global friend function
istream & operator >> (istream & input, Complex & obj)
{
// First check if the failbit is already set
if (input.fail())
{
return input; //if so, go home
}
ios_base::fmtflags origFormat; // Create format flag
origFormat = input.flags(); // save original flag setting
// Process '('
input.ignore(2, '('); // skip over '('
// Process real part
input >> obj.real_part; // read the real component of the Complex #
// Process ','
if (input.peek() == ',')
{
input.get(); // swallow ','
}
else // we have a problem
{
throw new Invalid_Mode1_Complex_Value_Exception(); // throw new exception
input.clear();
// restore format flags
input.flags(origFormat);
return input;
}
// Process imaginary part
// read the imaginary component of the Complex #
input >> obj.imaginary_part;
// Process ')'
if (input.peek() == ')')
{
input.get(); // swallow ')'
}
else // we have a problem
{
throw new Invalid_Mode1_Complex_Value_Exception(); // throw new exception
input.clear();
// restore format flags
input.flags(origFormat);
return input;
}
}
【问题讨论】:
-
请提供MCVE。至少,你好吗
throwing? -
嗨,巴里。很抱歉造成混乱。刚刚编辑了我的帖子。希望这是有道理的。