Espaços nominais
Variantes
Acções

throw expression

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.
jogar expressão
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
 
Sinaliza uma condição errônea e executa um manipulador de erro.
Original:
Signals an erroneous condition and executes an error handler.
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

throw expression (1)
throw (2)

[editar] Explicação

para mais informações sobre tentam' e capturas (manipulador de exceção) blocos
1)
A expressão throw constrói um objeto temporário em armazenagem não especificada, com o mesmo tipo como expression (com CV-qualificadores removido e o tipo de convertido a partir de matriz de T para ponteiro para T e de T para função retornando ponteiro para funcionar retornando T, conforme necessário) e inicializa-lo de expression da mesma maneira que um os argumentos da função ou valores de retorno são inicializados a partir dos parâmetros de função ou o argumento de uma expressão return (ou seja, elisão cópia e construção mudança ocorrer, se possível). O objeto de exceção persiste até o último cláusula catch completa ou até que o std::exception_ptr passado que faz referência a esse objeto é destruído.
Original:
The throw expression constructs a temporary object in unspecified storage, with the same type as expression (with cv-qualifiers removed and the type converted from array of T to pointer to T and from function returning T to pointer to function returning T, as necessary), and initializes it from expression in the same manner a function arguments or return values are initialized from the function parameters or the argument of a return expression (i.e. copy elision and move construction take place if possible). The exception object persists until the last catch clause completes or until the last std::exception_ptr that references this object is destroyed.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Uma vez que o objecto exceção é construído, o fluxo de controlo funciona para trás (para cima da pilha de chamadas) até que atinja o início de um bloco try, altura em que os parâmetros dos blocos catch associados são comparados com o expression atirado para encontrar uma correspondência. Se nenhuma correspondência é encontrada, o fluxo de controlo continua a desenrolar a pilha até que o bloco try seguinte, e assim por diante. Se uma correspondência for encontrada, o controle de fluxo de saltos para o bloco catch correspondência (o manipulador de exceção'), que executa normalmente.
Original:
Once the exception object is constructed, the control flow works backwards (up the call stack) until it reaches the start of a try block, at which point the parameters of the associated catch blocks are compared with the thrown expression to find a match. If no match is found, the control flow continues to unwind the stack until the next try block, and so on. If a match is found, the control flow jumps to the matching catch block (the exception handler), which executes normally.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
construída desde o correspondente bloco try-foi inserido, na ordem inversa da construção. Se uma exceção é lançada a partir de um construtor, destrutores são chamados para todas totalmente construídas não-estáticos não variantes membros e classes base. Este processo é chamado de' pilha desenrolamento.
Original:
As the control flow moves up the call stack, destructors are invoked for all objects with '
duração de armazenamento automático
Original:
automatic storage duration
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>
constructed since the corresponding try-block was entered, in reverse order of construction. If an exception is thrown from a constructor, destructors are called for all fully-constructed non-static non-variant members and base classes. This process is called stack unwinding.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
2)
O tiro de expressão sem um operando só pode ser utilizado dentro de um bloco catch (que chama std::terminate se usado de outra forma). Ele abandona a execução do bloco de captura e passa o controle para a próxima cláusula correspondência captura na pilha de chamada (mas não de uma outra cláusula capturas após o bloco try mesmo), reutilizando o objeto de exceção existente: há novos objetos são feitos.
Original:
The throw-expression without an operand may only be used inside a catch block (it calls std::terminate if used otherwise). It abandons the execution of the catch block and passes control to the next matching catch clause up the call stack (but not to another catch clause after the same try block), reusing the existing exception object: no new objects are made.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Veja std::terminate e std::unexpected para o tratamento de erros que surgem durante o tratamento de exceções.
Original:
See std::terminate and std::unexpected for the handling of errors that arise during exception handling.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Uso

Enquanto lance-expressão pode ser utilizada para transferir o controlo para um bloco de código arbitrário até a pilha de execução, por razões arbitrárias (semelhante ao std::longjmp), o seu uso pretendido é o tratamento de erros.
Original:
While throw-expression can be used to transfer control to an arbitrary block of code up the execution stack, for arbitrary reasons (similar to std::longjmp), its intended usage is error handling.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] De tratamento de erros

Lançando uma exceção é usada para sinalizar erros de funções, em que os "erros" são tipicamente limitadas a apenas o seguinte Erro de citação: </ref> de fecho em falta, para o elemento <ref>[1]:
Original:
{{{2}}}
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
# Falhas para estabelecer invariantes
Original:
# Failures to establish invariants
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Falhas # para atender as pós-condições
Original:
# Failures to meet the postconditions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Falhas # para atender os pré-requisitos do chamador
Original:
# Failures to meet the preconditions of the caller
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Em particular, isto implica que as falhas de construtores ea maioria dos operadores deve ser relatado lançando exceções.
Original:
In particular, this implies that the failures of constructors and most operators should be reported by throwing exceptions.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Segurança exceção

Após a condição de erro é relatado por uma função, garantias adicionais podem ser fornecidas em relação ao estado do programa. As seguintes quatro níveis de garantia exceção são geralmente reconhecidos B. Erro de citação: </ref> de fecho em falta, para o elemento <ref>[2][3], which are strict supersets of each other:
Original:
{{{2}}}
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
# Nothrow (ou nofail) garantia de exceção - nunca a função lança exceções.
Original:
# Nothrow (or nofail) exception guarantee -- the function never throws exceptions.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
# Garantia exceção Forte - Se a função lança uma exceção, o estado do programa é revertida para o estado pouco antes da chamada de função.
Original:
# Strong exception guarantee -- If the function throws an exception, the state of the program is rolled back to the state just before the function call.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
# Garantia exceção Básico - Se a função lança uma exceção, o programa está em um estado válido. Ele pode exigir a limpeza, mas todas as invariantes estão intactos.
Original:
# Basic exception guarantee -- If the function throws an exception, the program is in a valid state. It may require cleanup, but all invariants are intact.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
# Não há garantia de exceção - Se a função lança uma exceção, o programa não pode estar em um estado válido: vazamentos de recursos, corrupção de memória, ou outros invariante-destruindo erros podem ter ocorrido.
Original:
# No exception guarantee -- If the function throws an exception, the program may not be in a valid state: resource leaks, memory corruption, or other invariant-destroying errors may have occurred.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Objetos de exceção

Enquanto objetos de qualquer tipo completo e ponteiros cv para void podem ser jogados como objetos de exceção, todas as funções da biblioteca padrão jogar anônimos objetos temporários por valor, e os tipos de esses objetos são derivadas (direta ou indiretamente) de std::exception. Exceções definidas pelo usuário geralmente seguem esse padrão. D. Erro de citação: </ref> de fecho em falta, para o elemento <ref>[4]
Original:
{{{2}}}
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Para evitar cópias desnecessárias do objeto de exceção e objeto de corte, a melhor prática para cláusulas de captura é para pegar referência. S. Erro de citação: </ref> de fecho em falta, para o elemento <ref>[5][6]
Original:
{{{2}}}
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

throw

[editar] Exemplo

[editar] Referências

  1. H.Sutter, A. Alexandrescu (2004), "C++ Coding Standards", Item 70
  2. H. Sutter (2000) "Exceptional C++"
  3. D. Abrahams (2001) "Exception Safety in Generic Components"
  4. M. Cline, C++FAQ Lite 17.11
  5. M. Cline, C++FAQ Lite 17.12
  6. H.Sutter, A. Alexandrescu (2004) "C++ Coding Standards" Item 73
Original:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Veja também