try...catch

Esta traducción está incompleta. Por favor, ayuda a traducir este artículo del inglés.

see the talk page - this probably should just be "try"

Resumen

la declaración try...catch marca un bloque de instrucciones para intentar (try), y especifica una respuesta si se produce una excepción (catch). 

Sintaxis

try {try_statements
}
[catch (exception_var_1 ifcondition_1) {catch_statements_1
}]
...
[catch (exception_var_2) {catch_statements_2
}]
[finally {finally_statements
}]
try_statements
Las sentencias que serán ejecutadas.
catch_statements_1, catch_statements_2
Sentencias que son ejecutadas si una excepción es lanzada en el bloque try.
exception_var_1, exception_var_2
Identificador que contiene un objeto de excepciones asociada a cada clausula catch.
condition_1
Una expresión condicional.
finally_statements
Sentencias que se ejecutan después de que se complete la declaración try . Estas sentencias se ejecutan independientemente de si una excepcion se ha lanzado o capturado.

Descripción

La sentencia de try consiste un bloque try , esta contiene una o más instrucciones, y al menos una clausula catch o una finally , o bien ambas. Es decir, hay tres formas de declarar un sintaxis de try:

  1. try...catch
  2. try...finally
  3. try...catch...finally

Una bloque catch contiene instruccioes que especifican que hacer si se genera una excepción en el bloque try . Es decir, si usted decea que bloque try tenga éxito, pero si este no tiene éxito, el control pasa al bloque catch. Si cualquier sentencia dentro del bloque try (o una funcion llamada desde dentro del bloque try) lanza una excepción. el control cambia inmediatamente a la clausula catch . Si ninguna excepcion es lanzada por el bloque try , la clausula catch se omite.

La cláusula finally se ejecuta despues del bloque try y la(s) clausula(s) catch pero antes de las instrucciones que siguen a la sentencia try. Esta siempre se ejecuta, independientemente de si se ha producido o no una excepción.

You can nest one or more try statements. If an inner try statement does not have a catch clause, the enclosing try statement's catch clause is entered.

You also use the try statement to handle Java exceptions. See the JavaScript Guide for information on Java exceptions.

Cláusula incondicional catch

When a single, unconditional catch clause is used, the catch block is entered when any exception is thrown. For example, when the exception occurs in the following code, control transfers to the catch clause.

try {
   throw "myException"; // genera una excepción
}
catch (e) {
   // sentencias para manejar cualquier excepción
   logMyErrors(e); // pasar el objeto de la excepción al manejador de errores
}

Cláusulas condicionales catch

No estándar
This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

You can also use one or more conditional catch clauses to handle specific exceptions. In this case, the appropriate catch clause is entered when the specified exception is thrown. In the following example, code in the try block can potentially throw three exceptions: TypeError, RangeError, and EvalError. When an exception occurs, control transfers to the appropriate catch clause. If the exception is not one of the specified exceptions and an unconditional catch clause is found, control transfers to that catch clause.

If you use an unconditional catch clause with one or more conditional catch clauses, the unconditional catch clause must be specified last. Otherwise, the unconditional catch clause will intercept all types of exception before they can reach the conditional ones.

try {
   myroutine(); // may throw three exceptions
} catch (e if e instanceof TypeError) {
   // statements to handle TypeError exceptions
} catch (e if e instanceof RangeError) {
   // statements to handle RangeError exceptions
} catch (e if e instanceof EvalError) {
   // statements to handle EvalError exceptions
} catch (e) {
   // statements to handle any unspecified exceptions
   logMyErrors(e); // pass exception object to error handler
}

Note: This functionality is not part of the ECMAScript specification.

El identificador de excepciones

When an exception is thrown in the try block,exception_var (e.g. the e in catch (e)) holds the value specified by the throw statement. You can use this identifier to get information about the exception that was thrown.

This identifier is local to the catch clause. That is, it is created when the catch clause is entered, and after the catch clause finishes executing, the identifier is no longer available.

La cláusula finally

The finally clause contains statements to execute after the try block and catch clause(s) execute but before the statements following the try statement. The finally clause executes regardless of whether or not an exception is thrown. If an exception is thrown, the statements in the finally clause execute even if no catch clause handles the exception.

You can use the finally clause to make your script fail gracefully when an exception occurs; for example, you may need to release a resource that your script has tied up. The following example opens a file and then executes statements that use the file (server-side JavaScript allows you to access files). If an exception is thrown while the file is open, the finally clause closes the file before the script fails.

openMyFile()
try {
   // tie up a resource
   writeMyFile(theData);
}
finally {
   closeMyFile(); // always close the resource
}

Ejemplos

Vea los ejemplos para throw.

Vea también

Etiquetas y colaboradores del documento

Etiquetas: 
 Colaboradores en esta página: juanrapoport, habax, AlePerez92, SphinxKnight, teoli, Mgjbot, Talisker
 Última actualización por: juanrapoport,