我需要在主程序中添加一个或多个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;
}
}