抛出和捕获自定义异常

Throwing and Catching Custom Exceptions

我需要向我的主程序添加一个或多个 try 块和随附的 catch 处理程序。捕获处理程序将捕获由我的 class.

的重载提取运算符抛出的异常

我实现了重载提取运算符以抛出新的异常,但是我的主程序中的 catch 块似乎不是 working/catching 那些异常。

这是我的主程序的代码示例。

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;
    }
}

不需要运算符new,所以你throw语句

throw new Invalid_Mode1_Complex_Value_Exception(); 

应该是

throw Invalid_Mode1_Complex_Value_Exception(); 

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

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

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