/* IFT1169 - démonstration #04 - exercice 04 11-février -2006 v1.00 M.Lokbani - l'énoncé+solution + gcc3.4.2 à partir de l'énoncé de l'examen Final session été 2000 - IFT1166 - contact: lokbani@iro.umontreal.ca Copyright (C) 1999-2006 Université de Montréal Département d'informatique et de Recherche Opérationnelle Mohamed Lokbani -- Tous Droits Réservés -- All Rights Reserved -- Description: ------------ Définition des outils nécessaires pour lever les exceptions: overflow et underflow, sur de simples opérations mathématiques sur des entiers non signés (unsigned int). */ #include using namespace std; struct overflow { const char* msg; const char* fonction; }; struct underflow { const char* msg; const char* fonction; }; unsigned int add(unsigned int a, unsigned int b) throw (overflow); unsigned int sous(unsigned int a, unsigned int b) throw (underflow); unsigned int calc(unsigned int a, unsigned int b, unsigned int c) throw (overflow, underflow); void printErreur(const char* func, const char* msg); int main() { cout << "Nous allons calculer (a+(b-c))" << endl; int v1; cout << "Entrer a:"; cin >> v1; int v2; cout << "Entrer b:"; cin >> v2; cout << "Entrer c:"; int v3; cin >> v3; for (;;) { try { int resultat = calc(v1, v2, v3); cout << "Le résultat est " << resultat << endl; return 0; } catch (underflow& u) { cout << "Underflow dans:" << endl; printErreur(u.fonction,u.msg); cout << endl; cout << "Entrer une nouvelle valeur pour c:"; cin >> v3; } catch (overflow& o) { cout << "Overflow dans:" << endl; printErreur(o.fonction,o.msg); cout << endl; cout << "Entrer une nouvelle valeur pour a:"; cin >> v1; } catch (...) { cout << "Erreur sévère: exception inconnue"<< endl; return 1; } } return 0; } unsigned int add(unsigned int a, unsigned int b) throw (overflow){ unsigned int c = a+b; if (c < a || c < b) { overflow of; of.fonction = "add"; of.msg = "Overflow dans add"; throw of; } return c; } unsigned int sous(unsigned int a, unsigned int b) throw (underflow){ unsigned int c = a-b; if (c > a) { underflow uf; uf.fonction ="sous"; uf.msg = "Underflow dans sous"; throw uf; } return c; } unsigned int calc(unsigned int a, unsigned int b, unsigned int c) throw (overflow, underflow) { try { unsigned int resultat = add(a,sous(b,c)); return resultat; } catch (underflow& uf) { uf.fonction = "calc"; throw; } catch (overflow& of) { of.fonction = "calc"; throw; } } void printErreur(const char* fonct, const char* msg){ cout << " " << fonct << endl << endl << " \"" << msg << "\"" << endl; }