Exceptions, héritage et méthodes virtuelles
Bonjour,
Cela fait plusieurs heures que je bloque sur le problème suivant. Voici mon bout de code de test de l'architecture des exceptions pour mon projet :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| #include <iostream>
#include <string>
using namespace std;
// Classe de base des exceptions
class Exception {
public :
Exception() : next(NULL) {}
Exception& add(Exception& e) {
Exception* tmp = this;
while (tmp->next != NULL)
tmp = tmp->next;
tmp->next = &e;
return *this;
}
virtual string show() { return "Classe Exception"; }
Exception* next;
};
// Première exception
class ExceptionA : public Exception {
public:
virtual std::string show() { return "Classe ExceptionA"; }
};
// Seconde exception
class ExceptionB : public Exception {
public:
virtual std::string show() { return "Classe ExceptionB"; }
};
// Affichage;
ostream& operator<<(ostream& out, Exception& e) {
out << e.show() << endl;
if (e.next != NULL)
out << *e.next;
return out;
}
int main(int argc, char *argv[])
{
// Test d'une exception basique
try {
throw ExceptionA();
} catch (Exception& e) {
// On attend l'affichage :
// Class ExceptionA
cout << "Test simple :" << endl << e << endl;
}
// Test d'une exception en cascade n°1
try {
try {
throw ExceptionA();
} catch (Exception& e) {
ExceptionB b = ExceptionB();
b.add(e);
throw b;
}
} catch (Exception& e) {
// On attend l'affichage :
// Class ExceptionB
// Class ExceptionA
cout << "Test cascade n°1 :" << endl << e << endl;
}
// Test d'une exception en cascade n°2
try {
try {
throw ExceptionA();
} catch (Exception& e) {
throw ExceptionB().add(e);
}
} catch (Exception& e) {
// On attend l'affichage :
// Class ExceptionB
// Class ExceptionA
cout << "Test cascade n°2 :" << endl << e << endl;
}
return 0;
} |
Comme vous l'aurez probablement affiché il "foire" au test en cascade n°2 et m'affiche :
Code:
1 2 3
| Test cascade n°2 :
Classe Exception
Classe ExceptionA |
Vous avez une idée de la raison pour laquelle cela ne fait pas du tout ce que j'attends ? De plus la classe Exception ne sera jamais instanciée, je voulais en faire une classe abstraitre mais cela ne fonctionne pas avec l'envoi d'exceptions :/ c'est la raison pour laquelle j'ai défini la méthode Exception::show()
Merci beaucoup de votre aide.
Nuwanda