try-catch在try中检查多个对象

时间:2016-06-14 01:43:52

标签: c++ try-catch

我想知道像这样的代码是否总是会在抛出异常后不会继续,所以代码不会进入第二个temp.dodaj(b)。


    Avto *a = new Avto("lambo",4);
    Avto *b = new Avto("BMW",3);
    Avto *c = new Avto("lexus",6);
    SeznamAvtov temp;
    try {
        temp.dodaj(a);
        temp.dodaj(b);
        temp.dodaj(c); // here the exception will be thrown
        temp.dodaj(b);
    } catch(PokvarjenAvto &e) {
        e.error();
    }
    temp.pisi();

我的第二个问题是,是否可以抛出包含有关错误数据的对象,或者是一个异常& e使用const char * what()方法必须吗?

感谢您的回答

1 个答案:

答案 0 :(得分:1)

  

我想知道像这样的代码是否总是会在抛出异常后不会继续,所以代码不会进入第二个temp.dodaj(b)。

是的,它的行为与你描述的一样。

  

我的第二个问题是,是否可以抛出包含有关错误数据的对象,或者是一个异常& e使用const char * what()方法必须吗?

不,你可以扔任何你想要的类型。但是,常见的约定是异常类型应该从std::exception派生并覆盖const char* what()函数。