Accueil
|_Accueil Langage C++ |_Les mots clés C++ |_break |_continue |_do / while |_for |_for (foreach) |_goto |_if / else |_switch / case |_thread_local |_throw |_try / catch |_while |
Instruction try / catchSyntaxe d'utilisationtry { [statement]... } catch( ... ) { [statement]... } try { [statement]... } catch( const exceptiontype & exception ) { [statement]... }
Une exception correspond (comme son nom l'indique) à un état exceptionnel observé dans le système : la plupart du temps, cela correspond à un
état d'erreur. L'instruction
Deux fichiers d'entêtes sont intimement liés à cette instruction : l'entête
Notez qu'il existe une syntaxe particulière pour un bloc
Il est donc possible de définir plusieurs blocs Exemple de code#include <cstdlib> #include <ctime> #include <iostream> #include <stdexcept> using namespace std; /* Imagine a library that can throw an exception. */ double fct() { int value = rand() % 3; if ( value == 0 ) throw domain_error( "0 is a Bad value" ); return 1.0 / value; } /* Here an usage of this library */ int main() { srand( time( NULL ) ); try { cout << "Result == " << fct() << endl; } catch( const exception & e ) { cerr << e.what() << endl; } catch( ... ) { cerr << "Another unknown error" << endl; } return 0; } Sujets connexes |
Améliorations / Corrections
Vous avez des améliorations (ou des corrections) à proposer pour ce document : je vous remerçie par avance de m'en faire part, cela m'aide à améliorer le site.
Emplacement :
Description des améliorations :