【问题标题】:Throwing and Catching Custom Exceptions抛出和捕获自定义异常
【发布时间】: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?
  • 嗨,巴里。很抱歉造成混乱。刚刚编辑了我的帖子。希望这是有道理的。

标签: c++ exception-handling


【解决方案1】:

运算符new中不需要,所以你throw声明

throw new Invalid_Mode1_Complex_Value_Exception(); 

应该是

throw Invalid_Mode1_Complex_Value_Exception(); 

或者你需要捕获指针(但是这更糟糕,因为你需要检查它是否是nullptr

catch(Invalid_Mode1_Complex_Value_Exception* exception) {
    ....
}

引用和指针是不同的类型,所以你不能抛出一个并抓住另一个。看看thisthis

【讨论】:

  • 谢谢!我尝试了您的方法并进行了一些其他更改,现在可以使用了。
猜你喜欢
  • 2015-07-14
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-24
  • 2018-03-09
  • 2011-10-06
相关资源
最近更新 更多