throw expression
Da 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. |
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.
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) blocosOriginal:Seebloco try-catch</div> for more information about try and catch (exception handler) blocksOriginal:try-catch blockThe 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.
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.
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.
You can help to correct and verify the translation. Click here for instructions.
Como o fluxo de controle move-se a pilha de chamadas, destruidores são invocados para todos os objetos com '<div class="t-tr-text">duração de armazenamento automático
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:
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.
You can help to correct and verify the translation. Click [http://en.cppreference.com/w/Cppreference:MachineTranslations here] for instructions.
Original:
As the control flow moves up the call stack, destructors are invoked for all objects with '
duração de armazenamento automático</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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
You can help to correct and verify the translation. Click here for instructions.
[editar] Palavras-chave
[editar] Exemplo
Esta seção está incompleta |
[editar] Referências
- ↑ H.Sutter, A. Alexandrescu (2004), "C++ Coding Standards", Item 70
- ↑ H. Sutter (2000) "Exceptional C++"
- ↑ D. Abrahams (2001) "Exception Safety in Generic Components"
- ↑ M. Cline, C++FAQ Lite 17.11
- ↑ M. Cline, C++FAQ Lite 17.12
- ↑ 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.
You can help to correct and verify the translation. Click here for instructions.
[editar] Veja também
- <div class="t-tr-text"> bloco try-catch</div>Original:try-catch blockThe 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 class="t-tr-text"> noexcept especificador</div>Original:noexcept specifierThe 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 class="t-tr-text"> especificações de exceção</div>Original:exception specificationsThe 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.