程序的输出是什么-异常处理?

时间:2019-10-29 00:16:32

标签: c++ exception struct constructor

#include <iostream>

struct GeneralException {
  virtual void print() { std::cout << "G"; }
};

struct SpecialException : public GeneralException {
  void print() override { std::cout << "S"; }
};

void f() { throw SpecialException(); }

int main() {
  try {
    f();
  }
  catch (GeneralException e) {
    e.print();
  }
}

在main方法中,当调用f()时,它将抛出SpecialException。我很困惑会抛出SpecialException()吗?它将调用struct SpecialException(未定义)的构造函数。

3 个答案:

答案 0 :(得分:1)

代码:

throw SpecialException();

此默认构造一个SpecialException实例并将其抛出。 SpecialException没有注册的特定处理程序,但是基类GeneralException by-value 则有一个特定的处理程序,这意味着您的SpecialException实例将将其复制切片成GeneralException,结果是打印出来的.. G

如果您希望/期望打印S,则必须通过引用(最好是const)捕获该异常,这需要在两个实现中都将print设为const。结果将如下所示:

#include <iostream>

struct GeneralException {
    virtual void print() const { std::cout << "G"; }
};

struct SpecialException : public GeneralException {
    void print() const override { std::cout << "S"; }
};

void f() { throw SpecialException(); }

int main() {
    try {
        f();
    }
    catch (GeneralException const& e) {
        e.print();
    }
}

输出

S

答案 1 :(得分:0)

我认为您对捕捉和投掷如何工作感到困惑。 让我用一段代码展示一下。

       while(ch != 'n'){
       try{
        cout<<"Enter some number"'; // Let us suppose we want to  enter some int.
        cin>>num; // think that you enter char here.Ideally it show exit due to your input.But since we have made this statement in try block. It'll try to look for some handler who can handle such errors.
        cout<<"Wanna enter more. Enter y or n -"<<endl;
        cin>>ch;
        if(!cin){ // since you entered char when int was required. stream will corrupt.
            throw runtime_error("Input failed.\n");} // here we are throwing it.We are throwing it to runtime_error. It will search for it and go to that block.
    }
    catch(runtime_error error){ // This will catch it.
        cout<<error.what()
            <<"Try again? Enter y or n.\n";
            char c; //if you enter y it will go back to take input since it's while loop.
            cin>>c;
            if(!cin || c=='n'){
                break;
            }
    }
     }

答案 2 :(得分:0)

输出将为

G

简单地说,当您编写throw SpecialException()时,它只是创建SpecialException的对象并将其传递给catch块中的GeneralException e的对象。

换句话说,如果我把所有的东西放在一起,你可以假设这是实际发生的情况。

//throw statement    
SpecialException s;

//catch statment
GeneralException e = s;
e.print();

由此很明显,没有发生多态现象,e.print();将打印G,它是print()类中定义的GeneralException的版本。

要利用多态性,请更新@WhozCraig答案中已经提到的代码。

相关问题