// exception.cpp Création et utilisation d'exceptions // > deux CLASSES d'EXCEPTION // > exemple de lancement d'une exception de type double // > exemple de capture d'une exception de type double // auteur: R.Astier // // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + #include <iostream> #include <fstream> #include <string> using namespace std; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + class ExcFichier { public: ExcFichier(int e) : etat(e) { } string message(); protected: int etat; string msg; }; // Erreur sur fichier en lecture (entrée) class ExcFichierE : ExcFichier { public: string message() {return msg; }; ExcFichierE(char * txt, int e): ExcFichier(e) { msg += "* * (ExcFichierE) Fichier "; (msg += txt) += " non accessible en lecture"; } }; // Erreur sur fichier en sortie ou écriture class ExcFichierS : ExcFichier { public: string message() {return msg; } ; ExcFichierS(char * txt, int e): ExcFichier(e) { msg += "* * (ExcFichierE) Fichier '"; (msg += txt) += "' ne peut pas être créé"; } private: int etat; }; string lireFic(char nomFic[]) throw (ExcFichierE) { ifstream fic(nomFic,ios::ate); if(!fic) throw ExcFichierE(nomFic, fic.rdstate()); long taille=fic.tellg(); cout << "taille de "<< nomFic << ": "<<taille << endl; // Revenir au début, lire le contenu et fermer le fichier fic.seekg(0,ios::beg); char * pmem=new char[1+taille]; fic.read(pmem,taille); pmem[taille]='\0'; fic.close(); string txt = string(pmem,taille); delete[] pmem; return txt; } void ecrireFic(string txt, char nomFic[]) throw (ExcFichierS) { ofstream fic(nomFic,ios::binary); if(!fic) throw ExcFichierS(nomFic, fic.rdstate()); fic.write(txt.c_str(),txt.length()); fic.close(); } double division(double a, double b) throw (double) { if(b==0) throw a; return a/b; } // Moyennne des n premiers entiers // propagation de l'exception double vitesse(double d, double t) throw (double) { return division(d,t); } //- - - - - - - - Q u e l q u e s u t i l i s a t i o n s - - - - -+ int main( int ntm, char *tm[]) { double dist,duree; cout<<"distance ? "; cin>>dist; cout<<"durée ? "; cin>>duree; try { cout<< "Vitesse "<< vitesse(dist,duree)<<endl; } catch(double d) { cout<<"division "<<d<<"/0 impossible"<<endl; } try { "vitesse(3.14,0) ==> "<< vitesse(3.14,0)<<endl; } catch(double d) { cout<<"division "<<d<<"/0 impossible"<<endl; } cout<<"Fin exception 'double'"<<endl; string txt; try { txt=lireFic("exception.cpp"); cout <<" -> longueur: " << txt.length() << endl; ecrireFic(txt,"toto"); } catch(ExcFichierE e) { cout<<e.message(); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + return 0; } //fin exception.cpp