Espaços nominais
Variantes
Acções

try-catch statement

Da cppreference.com
< cpp‎ | language

 
 
Linguagem C++
Tópicos gerais
Original:
General topics
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Controle de fluxo
Original:
Flow control
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Declarações execução condicional
Original:
Conditional execution statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Instruções de iteração
Original:
Iteration statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Ir declarações
Original:
Jump statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Funções
Original:
Functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
declaração da função
lambda declaração da função
modelo de função
linha especificador
especificações de exceção (obsoleta)
noexcept especificador (C++11)
Exceções
Original:
Exceptions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
bloco try-catch
Namespaces
Original:
Namespaces
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Tipos
Original:
Types
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
decltype specifier (C++11)
Especificadores
Original:
Specifiers
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
cv especificadores
armazenamento duração especificadores
constexpr especificador (C++11)
auto especificador (C++11)
alignas especificador (C++11)
Inicialização
Original:
Initialization
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Literais
Original:
Literals
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Expressões
Original:
Expressions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
representações alternativas
Utilitários
Original:
Utilities
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Tipos
Original:
Types
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
typedef declaration
tipo de alias declaração (C++11)
atributos (C++11)
Conversões
Original:
Casts
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
conversões implícitas
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
Elenco C-estilo e funcional
Alocação de memória
Original:
Memory allocation
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Classes
Original:
Classes
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Classe propriedades específicas de função
Original:
Class-specific function properties
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Funções membro especiais
Original:
Special member functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Modelos
Original:
Templates
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
modelo de classe
modelo de função
especialização de modelo
pacotes de parâmetros (C++11)
Diversos
Original:
Miscellaneous
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Assembly embutido
 
Utilizado para tentar a execução de uma instrução composto, enquanto que a captura e movimentação excepções que podem ter sido geradas como um resultado desta tentativa.
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.

Índice

[editar] Sintaxe

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)

[editar] Explicação

para mais informações sobre exceções lance
A sintaxe básica (1) mostra os componentes básicos de um bloco try-catch. Em primeiro lugar, a palavra-chave try inicia um bloco try em que statements pode ser executado. Note que o bloco try, a partir da chave de abertura para o seu fechamento, segue as mesmas regras de escopo como qualquer outro escopo (por exemplo, as variáveis ​​declaradas dentro do bloco try não estão disponíveis fora dele, inclusive do bloco catch que segue ). Em seguida, a declaração catch atua como um especificador do tipo de exceção a ser capturado se jogado de dentro do bloco try. O exception-decl tem a mesma sintaxe da declaração de parâmetro dentro de um único parâmetro declaração de função (exceto que o tipo não pode, por void, um tipo incompleto, ou um rvalue-referência (desde C++11)). Finalmente, o composto declaração- { statements que seguem o catch-é chamado de' manipulador de exceção e contém instruções a serem executadas em resposta à exceção que foi pego. Código de tratamento de exceção típico inclui log de erro, empregando um método alternativo ao que foi feito no bloco try, ou re-embalagem a exceção em uma outra exceção lançada com informações adicionais.
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 (desde 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.
Na sintaxe (2), a ilustração que aqui é um bloco de teste de captura, não se limita a um único bloco catch. Desde diferentes tipos de exceções podem ser geradas de dentro do bloco try, pode-se especificar até pegar-blocos forem necessárias para lidar com todas as exceções que se deseja tratar. Note, no entanto, que a ordem de apresentação das declarações de captura é importante, uma exceção gerada será tratado pelo primeiro bloco catch, por ordem de aparecimento, cujo exception-decl é uma partida válida (e conversões implícitas aplicar também). Em outras palavras, é não a melhor jogo que é escolhido (como em regras a sobrecarga de função), mas o jogo em primeiro lugar. Se a exceção lançada corresponde nenhuma das declarações de capturas, então a exceção é levado de volta até que outro encerrando bloco try é alcançado ou até que o programa é encerrado devido a uma exceção não tratada.
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.
Na sintaxe (3), a única adição é a afirmação throw; dentro do bloco catch. A declaração tem o efeito de re-lançando o objeto de exceção mesmo que foi pego pelo bloco catch. Este é o único contexto em que um vazio declaração lance é válido, e é significado específico é a re-lançar a exceção que foi pego, e declarou como 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.
Sintaxe (4) é um assim chamado' pega-tudo bloco. O operador reticências' ... (literalmente, três pontos) pode ser usado em lugar do exception-decl para especificar que todos e quaisquer tipos de exceções devem ser pego pelo bloco catch. Este tipo de bloco catch-all não é útil para obter qualquer informação sobre o tipo de exceção que foi lançada, e uma vez que a maioria dos objetos de exceção são de classes derivadas de <div class="t-tr-text"> std :: exceção
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.
, geralmente é mais útil para capturar a exceção como catch( std::exception& e ). No entanto, o principal objetivo de um bloco catch-all é para garantir que não são exceções.Ele vazou de uma função, o que é especialmente útil para funções especiais de que vazamento de exceções podem ser perigosos, principalmente, um destruidor ou um externo dinamicamente ligado função.
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 :: exceção
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.
</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.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Sintaxe (5) é chamado de' função bloco try e pode ser usado para colocar um corpo função inteira dentro de um bloco try (com catch-blocos seguindo-o). Isto é especialmente útil para capturar exceções que podem ser geradas durante a execução de uma lista de inicialização do construtor (construção de sub-objetos de uma classe), de facto, é a única maneira de o fazer. Este função bloco try sintaxe é raramente usada em qualquer outro contexto, pois não tem nenhuma vantagem em relação a um bloco try-catch tradicional, ea sintaxe resultante é geralmente pouco atraente (e desconhecido para a maioria).
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.

[editar] Palavras-chave

try, catch, throw

[editar] Exemplo

O exemplo seguinte demonstra a utilização de vários processos do bloco 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.

#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";
    }
 
}

Saída:

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'