Espacios de nombres
Variantes
Acciones

try-catch statement

De cppreference.com
< cpp‎ | language

 
 
Lenguaje C++
Los temas generales
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.
Control de flujo
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.
Sentencias condicionales ejecución
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.
Instrucciones de iteración
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 declaraciones
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.
Funciones
Original:
Functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
declaración de la función
lambda declaración de la función
función de plantilla
especificador inline
especificaciones de excepción (obsoleto)
noexcept especificador (C++11)
Excepciones
Original:
Exceptions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
bloque try-catch
Los espacios de nombres
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)
Los 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
almacenamiento duración especificadores
constexpr especificador (C++11)
auto especificador (C++11)
alignas especificador (C++11)
Inicialización
Original:
Initialization
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Los literales
Original:
Literals
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Expresiones
Original:
Expressions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
representaciones alternativas
Utilidades
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
alias de tipo de declaración (C++11)
atributos (C++11)
Lanza
Original:
Casts
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
conversiones implícitas
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-cast estilo y funcional
De asignación de memoria
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.
Clases
Original:
Classes
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Clase propiedades específicas de la función
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.
Funciones especiales miembro
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.
Plantillas
Original:
Templates
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
clase de plantilla
función de plantilla
plantilla de especialización
paquetes de parámetros (C++11)
Varios
Original:
Miscellaneous
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Montaje en línea
 
Se utiliza para tratar la ejecución de un compuesto-afirmación, mientras que la captura y el manejo de excepciones que pueden haber sido lanzadas como resultado de este intento .
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.

Contenido

[editar] Sintaxis

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] Explicación

para obtener más información acerca de las excepciones tiro
La sintaxis básica (1) muestra los componentes básicos de un bloque try-catch. En primer lugar, la palabra clave try inicia un intento de bloque en el que statements puede ser ejecutado. Tenga en cuenta que el try-block, desde la apertura rizado corsé para su cierre, sigue las mismas reglas de alcance que cualquier otro ámbito (por ejemplo variables declaradas dentro del bloque try-no están disponibles fuera de ella, incluso desde el bloque catch que le sigue ). Entonces, la instrucción catch actúa como un especificador de tipo de excepción a ser capturados si son lanzados desde dentro del bloque try-. El exception-decl tiene la misma sintaxis que la declaración de parámetros dentro de un solo parámetro declaración de función (excepto que el tipo no puede por void, un tipo incompleto, o una referencia de valor p-(desde C++11)). Por último, el compuesto declaración { statements que siguen el catch-declaración se llama el gestor de excepciones y contiene sentencias que se ejecutan en respuesta a la excepción de que fue capturado. Típico de excepciones código incluye la tala de error, empleando un método alternativo a lo que se intentó en el try-block, o reenvasado la excepción a otra excepción que se produce con la información adicional .
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.
En la sintaxis (2), la ilustración aquí es que un bloque try-catch no se limita a una sola captura de bloque. Dado que los diferentes tipos de excepciones pueden ser lanzadas desde el try-block, se puede especificar hasta coger bloques como sea necesario para manejar todas las excepciones que se desea controlar. Tenga en cuenta, sin embargo, que el orden de aparición de los estados-captura es importante, una excepción que será manejada por el primer bloque catch, por orden de aparición, cuyo exception-decl es una coincidencia (y las conversiones implícitas se aplican también). En otras palabras, no es' la mejor coincidencia que se elige (como en las reglas de la sobrecarga de funciones), pero el partido primero. Si la excepción que coincide con ninguna de las declaraciones de capturas-, la excepción se lleva de nuevo hasta que otro bloque try-encierra se alcance o hasta que el programa se termina debido a una excepción no controlada .
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.
En la sintaxis (3), la única adición es la declaración throw; dentro del bloque catch. La declaración tiene el efecto de volver a lanzar la misma excepción objeto que fue capturado por el bloque catch. Este es el único contexto en el que una banda vacía declaración es válida, y su significado específico es volver a lanzar la excepción de que fue capturado y declarado 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.
Sintaxis (4) es el llamado catch-all bloque. El operador de puntos suspensivos' ... (literalmente, tres puntos) se puede utilizar en lugar del de la exception-decl para especificar que cualquier y todos los tipos de excepciones debe ser capturado por la captura de bloque. Este tipo de cajón de sastre bloque no es útil para obtener información sobre el tipo de excepción que se produjo, y puesto que la mayoría de los objetos de excepción son de clases derivadas de <div class="t-tr-text"> std :: excepción
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.
, generalmente es más útil para detectar la excepción como catch( std::exception& e ). Sin embargo, el propósito principal de un cajón de sastre bloque es para asegurar que no haya excepciones no capturadas se filtró de una función, que es especialmente útil para las funciones especiales de la que escapa excepciones pueden ser peligrosos, sobre todo, un destructor o un externo enlazado dinámicamente función .
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 :: excepción
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.
Sintaxis (5) se llama una función-try-block y se puede usar para encerrar un cuerpo de la función entera dentro de un try-block (con bloques catch-lo siguiente). Esto es especialmente útil para capturar las excepciones que puedan ser lanzados durante la ejecución de la lista de inicialización de un constructor (construcción de sub-objetos de una clase), de hecho, es la única manera de hacerlo. Esta función-try-block sintaxis se utiliza raramente en cualquier otro contexto, ya que no tiene ninguna ventaja en comparación con el tradicional bloque try-catch, y la sintaxis resultante es generalmente poco atractivo (y desconocido para la mayoría) .
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] Palabras clave

try, catch, throw

[editar] Ejemplo

El siguiente ejemplo muestra varios casos de uso del bloque 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";
    }
 
}

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'