try-catch statement
De cppreference.com
![]() |
This page has been machine-translated from the English version of the wiki using Google Translate.
The translation may contain errors and awkward wording. Hover over text to see the original version. You can help to fix errors and improve the translation. For instructions click here. |
Utilisé pour tenter l'exécution d'une instruction-composée, tandis que la capture et la gestion des exceptions qui peuvent avoir été lancées à la suite de cette tentative .
Original:
Used to attempt the execution of a compound-statement, while catching and handling exceptions that may have been thrown as a result of this attempt.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Sommaire |
[modifier] Syntaxe
try { statements } catch ( exception-decl ) { statements }
|
(1) | ||||||||
try { statements } catch ( exception-decl-1 ) { statements } catch ( exception-decl-2 ) { statements }
|
(2) | ||||||||
try { statements } catch ( exception-decl ) { statements throw; }
|
(3) | ||||||||
try { statements } catch ( ... ) { statements }
|
(4) | ||||||||
try : ctor-init-list { statements } catch ( exception-decl ) { statements }
|
(5) | ||||||||
[modifier] Explication
- Voir pour plus d'informations sur les exceptions lancersOriginal:Seelever des exceptions</div> for more information about throw exceptionsOriginal:throw exceptionsThe text has been machine-translated via [http://translate.google.com Google Translate].
You can help to correct and verify the translation. Click [http://en.cppreference.com/w/Cppreference:MachineTranslations here] for instructions.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
La syntaxe de base (1) présente les composants de base d'un bloc try-catch. Tout d'abord, le mot
try
initie un essai-bloc dans lequel statements peut être exécuté. Notez que l'instruction try-bloc, à partir de l'ouverture accolades sa fermeture, suit les mêmes règles que n'importe quel champ de portée d'autres (par exemple les variables déclarées dans le bloc try-ne sont pas disponibles à l'extérieur de celui-ci, y compris de la capture-bloc qui suit ). Ensuite, l'instruction catch
agit comme un spécificateur de type d'exception d'être pris à l'intérieur, si la jetée try-bloc. Le exception-decl a la même syntaxe que la déclaration de paramètres dans un seul paramètre déclaration de fonction (sauf que le type ne peut pas par void, un type incomplet, ou un rvalue référence (depuis C++11)). Enfin, l'instruction-composée {
statements }
qui suivent la catch-déclaration est appelé le exception-handler et contient des instructions à exécuter en réponse à l 'exception qui a été pris. Typique exception du code de gestion comprend l'enregistrement de l'erreur, en employant une méthode alternative à ce qui a été tenté dans le try-bloc, ou au reconditionnement l'exception dans un autre exception levée des informations supplémentaires .Original:
The basic syntax (1) shows the basic components of a try-catch block. First, the keyword
try
initiates a try-block in which statements can be executed. Note that the try-block, from the opening curly-brace to its closing, follows the same scoping rules as any other scope (e.g. variables declared within the try-block are not available outside of it, including from the catch-block that follows). Then, the catch
statement acts as a specifier of the type of exception to be caught if thrown from within the try-block. The exception-decl has the same syntax as the parameter declaration within a single-parameter function declaration (except that the type cannot by void, an incomplete type, or an rvalue-reference (depuis C++11)). Finally, the compound-statement {
statements }
which follow the catch-statement is called the exception-handler and contains statements to be executed in response to the exception that was caught. Typical exception-handling code includes logging the error, employing an alternative method to what was attempted in the try-block, or re-packaging the exception into another thrown exception with additional information.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Dans la syntaxe (2), l'illustration, c'est que un bloc try-catch n'est pas limité à une catégorie fourre-bloc unique. Depuis différents types d'exceptions peuvent être jetés à l'intérieur du bloc try-, on peut spécifier autant de blocs catch-que nécessaire pour gérer toutes les exceptions on souhaite traiter. Notez, cependant, que l'ordre d'apparition des états fourre-est important, levée d'une exception seront traitées par le fourre-premier bloc, par ordre d'apparition, dont exception-decl est une correspondance valide (et les conversions implicites s'appliquent aussi bien). En d'autres termes, il est pas le meilleur match qui est choisie (comme dans les règles de surcharge de fonction), mais le premier match'. Si l'exception renvoyée correspond à aucune des déclarations de capture-, l'exception est reportée jusqu'à ce qu'un autre joignant try-bloc est atteinte ou que le programme est terminé à cause d'une exception non gérée .
Original:
In syntax (2), the illustration here is that a try-catch block is not limited to a single catch-block. Since different types of exceptions can be thrown from within the try-block, one can specify as many catch-blocks as necessary to handle all exceptions one wishes to handle. Note, however, that the order of appearance of the catch-statements is important, a thrown exception will be handled by the first catch-block, by order of appearance, whose exception-decl is a valid match (and implicit conversions apply as well). In other words, it is not the best match that is chosen (as in function overloading rules), but the first match. If the thrown exception matches none of the catch-statements, then the exception is carried back until another enclosing try-block is reached or until the program is terminated due to an unhandled exception.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Dans la syntaxe (3), le seul ajout est la déclaration
throw;
dans le fourre-bloc. La déclaration a pour effet de re-jeter l'objet même exception qui a été capturé par la prise du bloc. C'est le seul contexte dans lequel un vide remise déclaration est valide, et il a une signification spécifique est de re-lever l'exception qui a été pris, et a déclaré que exception-decl .Original:
In syntax (3), the only addition is the
throw;
statement within the catch-block. The statement has the effect of re-throwing the same exception object which was caught by the catch-block. This is the only context in which an empty throw-statement is valid, and it's specific meaning is to re-throw the exception that was caught, and declared as exception-decl.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Syntaxe (4) est un soi-disant fourre-tout bloc. L'opérateur ellipse'
, il est généralement plus utile pour rattraper l'exception que catch( std::exception& e ). Toutefois, le but principal d'un fourre-tout bloc est de veiller à ce qu'aucun exceptions non rattrapées sont échappés de la fonction, ce qui est particulièrement utile pour les fonctions spéciales dont fuites exceptions peuvent être dangereux, surtout, un destructeur ou un externe liée dynamiquement fonction ....
(littéralement, trois points) peut être utilisé en place de la exception-decl de préciser que les types et toutes les exceptions de devraient être couvertes par la prise du bloc. Ce type de bloc catch-all n'est pas utile pour obtenir des informations sur le type d'exception qui a été levée, et depuis la plupart des objets d'exception sont des classes dérivées de <div class="t-tr-text"> std :: exceptionOriginal:
std::exception
The text has been machine-translated via [http://translate.google.com Google Translate].
You can help to correct and verify the translation. Click [http://en.cppreference.com/w/Cppreference:MachineTranslations here] for instructions.
You can help to correct and verify the translation. Click [http://en.cppreference.com/w/Cppreference:MachineTranslations here] for instructions.
Original:
Syntax (4) is a so-called catch-all block. The ellipsis operator
...
(literally, three dots) can be used in-place of the exception-decl to specify that any and all types of exceptions should be caught by the catch-block. This type of catch-all block is not useful for getting any information on the type of exception that was thrown, and since most exception objects are of classes derived from std :: exception</div>, it is generally more useful to catch the exception as catch( std::exception& e ). However, the main purpose of a catch-all block is to ensure that no uncaught exceptions are leaked from a function, which is especially useful for special functions from which leaking exceptions can be dangerous, most notably, a destructor or a dynamically-linked external function.
Original:
std::exception
The text has been machine-translated via [http://translate.google.com Google Translate].
You can help to correct and verify the translation. Click [http://en.cppreference.com/w/Cppreference:MachineTranslations here] for instructions.
You can help to correct and verify the translation. Click [http://en.cppreference.com/w/Cppreference:MachineTranslations here] for instructions.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Syntaxe (5) est appelé un fonction-try-bloc et peut être utilisé pour entourer un corps de la fonction entière à l'intérieur d'un bloc try-(avec catch-blocs qui la suit). Ceci est particulièrement utile pour intercepter des exceptions qui pourraient être projetés lors de l'exécution de la liste d'initialisation d'un constructeur (construction de sous-objets d'une classe), en fait, c'est la seule façon de le faire. Cette fonction-try-bloc de syntaxe est rarement utilisé dans un autre contexte, car il ne présente aucun avantage par rapport à un traditionnel bloc try-catch, et la syntaxe en résulte est généralement peu attrayant (et inconnu pour la plupart) .
Original:
Syntax (5) is called a function-try-block and can be used to enclose an entire function body inside a try-block (with catch-blocks following it). This is especially useful to catch exceptions which could be thrown during the execution of a constructor's initialization list (construction of sub-objects of a class), in fact, it is the only way to do so. This function-try-block syntax is seldom used in any other context because it has no advantage as compared to a traditional try-catch block, and the resulting syntax is generally unappealing (and unfamiliar to most).
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[modifier] Mots-clés
[modifier] Exemple
L'exemple suivant illustre l'utilisation de plusieurs cas du bloc
try-catch
Original:
The following example demonstrates several usage cases of the
try-catch
block
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
#include <iostream> #include <vector> int main() { try { std::cout << "Throwing an integer exception...\n"; throw int(42); } catch( int i ) { std::cout << " the integer exception was caught, with value: " << i << '\n'; } try { std::cout << "Creating a vector of size 5... \n"; std::vector<int> v(5); std::cout << "Accessing the 11th element of the vector...\n"; v.at(10); // the at() function will check the range. } catch( std::exception& e) { std::cout << " a standard exception was caught, with message '" << e.what() << "'\n"; } }
Résultat :
Throwing an integer exception... the integer exception was caught, with value: 42 Creating a vector of size 5... Accessing the 11th element of the vector... a standard exception was caught, with message 'out_of_range'