try-catch statement
Da cppreference.com.
![]() | Questa pagina è stata tradotta in modo automatico dalla versione in ineglese della wiki usando Google Translate. La traduzione potrebbe contenere errori e termini strani. Muovi il puntatore sopra al testo per vedere la versione originale. Puoi aiutarci a correggere gli gli errori. Per ulteriori istruzioni clicca qui. |
Utilizzato per tentare l'esecuzione di un composto-dichiarazione, mentre la cattura e la gestione delle eccezioni che possono essere state generate come risultato di questo tentativo.
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.
Indice |
[modifica]Sintassi
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) | ||||||||
[modifica]Spiegazione
- per ulteriori informazioni sulle eccezioni tiroOriginal:Seegenerare eccezioni</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 sintassi di base (1) mostra i componenti di base di un blocco try-catch. In primo luogo, la parola chiave
try
avvia un try-blocco in cui statements può essere eseguito. Si noti che il try-block, dall'apertura di parentesi graffe per la sua chiusura, segue le stesse regole di ambito di qualsiasi altro ambito (ad esempio, le variabili dichiarate all'interno del blocco try-non sono disponibili al di fuori di esso, anche dal blocco catch che segue ). Quindi, l'istruzione catch
agisce come un identificatore del tipo di eccezione da catturare se gettati all'interno del try-block. Il exception-decl ha la stessa sintassi della dichiarazione del parametro all'interno di un singolo parametro di dichiarazione di funzione (tranne che il tipo non può da void, un tipo incompleto, o un rvalue riferimento (dal C++11)). Infine, il composto-dichiarazione {
statements }
che seguono il fermo-istruzione viene chiamato eccezioni gestore e contiene istruzioni da eseguire in risposta alla eccezione che è stato catturato. Tipico di gestione delle eccezioni codice include registrazione di errore, utilizzando un metodo alternativo a quello che è stato tentato nel try-block, o al riconfezionamento l'eccezione in un altro eccezione generata con informazioni aggiuntive.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 (dal 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.
Nella sintassi (2), l'illustrazione è che un blocco try-catch non è limitata a un singolo catch-block. Dal momento che i diversi tipi di eccezioni possono essere generate all'interno del try-block, si possono specificare come molti di cattura blocchi necessari per gestire tutte le eccezioni che si vuole gestire. Si noti, tuttavia, che l'ordine di apparizione delle catture-affermazioni è importante, un eccezione generata saranno gestite dal primo blocco catch, in ordine di apparizione, il cui exception-decl è un match valido (e le conversioni implicite applicabili). In altre parole, non è il migliore partita che viene scelto (come nelle regole di overloading di funzioni), ma il primo partita. Se l'eccezione generata corrisponde a nessuna delle catture-dichiarazioni, l'eccezione viene riportata fino ad un altro che racchiude try-block o fino a quando il programma è terminato a causa di un'eccezione non gestita.
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.
Nella sintassi (3), l'unica aggiunta è l'istruzione
throw;
all'interno del catch-block. L'istruzione ha l'effetto di ri-lancio lo stesso oggetto eccezione che è stato catturato dal catch-blocco. Questo è l'unico contesto in cui un vuoto laterale affermazione è valida, e il suo significato specifico è quello di ri-lanciare l'eccezione che è stato catturato, e dichiarati come 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.
Sintassi (4) è un cosiddetto catch-all blocco. L'operatore puntini di sospensione'
, è generalmente più utile per catturare l'eccezione catch(std::exception& e ). Tuttavia, lo scopo principale di un catch-all blocco è per garantire che non le eccezioni non gestite sono trapelate da una funzione, che è particolarmente utile per le funzioni speciali da cui perdite eccezioni possono essere pericolose, in particolare, un distruttore o dinamicamente esterno collegato funzione....
(letteralmente, tre punti) può essere utilizzato in luogo del exception-decl per specificare che i tipi di ogni e qualsiasi di eccezioni dovrebbero essere catturato dal catch-blocco. Questo tipo di catch-all blocco non è utile per ottenere informazioni sul tipo di eccezione che è stato gettato, e dato che la maggior parte degli oggetti eccezione sono di classi derivate da <div class="t-tr-text"> std :: eccezioneOriginal:
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 :: eccezione</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.
Sintassi (5) viene chiamata una funzione-try-block' e possono essere utilizzate per racchiudere un intero corpo funzione all'interno di un blocco try-(con cattura blocchi seguendo). Ciò è particolarmente utile per rilevare le eccezioni che potrebbero essere generate durante l'esecuzione di elenco di inizializzazione di un costruttore (costruzione di sub-oggetti di una classe), infatti, è l'unico modo per farlo. Questa funzione-try-block sintassi' è raramente usato in qualsiasi altro contesto, perché non ha alcun vantaggio rispetto ad un tradizionale blocco try-catch, e la sintassi risultante è generalmente poco attraente (e sconosciuto per la maggior parte).
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.
[modifica]Parole chiave
[modifica]Esempio
L'esempio seguente mostra diversi casi di utilizzo del blocco
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";throwint(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";} }
Output:
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'