Ich habe ein Problem mit dem folgenden Code. Wie wir sehen können, habe ich bereits die Exception behandelt, die von As Konstruktor in Cs Konstruktor geworfen wurde. Warum sollte ich mich darum kümmern, die Exception in der Hauptfunktion wieder zu erfassen und zu behandeln?C++ - Konstruktor Initialisierungsliste werfen Ausnahmen
#include <iostream>
class WException : public std::exception
{
public:
WException(const char* info) : std::exception(info){}
};
class A
{
public:
A(int a) : a(a)
{
std::cout << "A's constructor run." << std::endl;
throw WException("A constructor throw exception.");
}
private:
int a;
};
class B
{
public:
B(int b) : b(b)
{
std::cout << "B's constructor body run." << std::endl;
throw WException("B constructor throw exception");
}
private:
int b;
};
class C : public A, public B
{
public:
C(int a, int b) try : A(a), B(b)
{
std::cout << "C's constructor run." << std::endl;
}
catch(const WException& e)
{
std::cerr << "In C's constructor" << e.what() << std::endl;
}
};
int main(int argc, char* argv[])
{
try
{
C c(10, 100);
}
catch(const WException& e)
{
std::cerr << "In the main: " << e.what() << std::endl;
}
return 0;
}
Hat eigentlich die Ausnahme von 'C' Konstruktor propagieren? Wenn nicht, warum fangen Sie es wieder? – arne
Wer hat vorgeschlagen, die Ausnahme in 'main()' auch zu fangen? Stellen Sie ihm diese Frage! – Nawaz
@Nawaz, Oder sie, meine Güte. Es ist kein Wunder, dass es in diesem Beruf keine Frauen gibt: p – chris