# Copyright (C) 2001-2020, Python Software Foundation # This file is distributed under the same license as the Python package. # Maintained by the python-doc-es workteam. # docs-es@python.org / # https://mail.python.org/mailman3/lists/docs-es.python.org/ # Check https://github.com/python/python-docs-es/blob/3.8/TRANSLATORS to # get the list of volunteers # msgid "" msgstr "" "Project-Id-Version: Python 3.8\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2023-10-12 19:43+0200\n" "PO-Revision-Date: 2023-11-01 15:15+0100\n" "Last-Translator: Marcos Medrano \n" "Language-Team: python-doc-es\n" "Language: es\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" "Generated-By: Babel 2.13.0\n" "X-Generator: Poedit 3.4\n" #: ../Doc/tutorial/errors.rst:5 msgid "Errors and Exceptions" msgstr "Errores y excepciones" #: ../Doc/tutorial/errors.rst:7 msgid "" "Until now error messages haven't been more than mentioned, but if you have " "tried out the examples you have probably seen some. There are (at least) " "two distinguishable kinds of errors: *syntax errors* and *exceptions*." msgstr "" "Hasta ahora los mensajes de error apenas habían sido mencionados, pero si " "has probado los ejemplos anteriores probablemente hayas visto algunos. Hay " "(al menos) dos tipos diferentes de errores: *errores de sintaxis* y " "*excepciones*." #: ../Doc/tutorial/errors.rst:15 msgid "Syntax Errors" msgstr "Errores de sintaxis" #: ../Doc/tutorial/errors.rst:17 msgid "" "Syntax errors, also known as parsing errors, are perhaps the most common " "kind of complaint you get while you are still learning Python::" msgstr "" "Los errores de sintaxis, también conocidos como errores de interpretación, " "son quizás el tipo de queja más común que tenés cuando todavía estás " "aprendiendo Python::" #: ../Doc/tutorial/errors.rst:26 msgid "" "The parser repeats the offending line and displays a little 'arrow' pointing " "at the earliest point in the line where the error was detected. The error " "is caused by (or at least detected at) the token *preceding* the arrow: in " "the example, the error is detected at the function :func:`print`, since a " "colon (``':'``) is missing before it. File name and line number are printed " "so you know where to look in case the input came from a script." msgstr "" "El intérprete reproduce la línea responsable del error y muestra una pequeña " "'flecha' que apunta al primer lugar donde se detectó el error. El error ha " "sido provocado (o al menos detectado) en el elemento que *precede* a la " "flecha: en el ejemplo, el error se detecta en la función :func:`print`, ya " "que faltan dos puntos (``':'``) antes del mismo. Se muestran el nombre del " "archivo y el número de línea para que sepas dónde mirar en caso de que la " "entrada venga de un programa." #: ../Doc/tutorial/errors.rst:37 msgid "Exceptions" msgstr "Excepciones" #: ../Doc/tutorial/errors.rst:39 msgid "" "Even if a statement or expression is syntactically correct, it may cause an " "error when an attempt is made to execute it. Errors detected during " "execution are called *exceptions* and are not unconditionally fatal: you " "will soon learn how to handle them in Python programs. Most exceptions are " "not handled by programs, however, and result in error messages as shown " "here::" msgstr "" "Incluso si una declaración o expresión es sintácticamente correcta, puede " "generar un error cuando se intenta ejecutar. Los errores detectados durante " "la ejecución se llaman *excepciones*, y no son incondicionalmente fatales: " "pronto aprenderás a gestionarlos en programas Python. Sin embargo, la " "mayoría de las excepciones no son gestionadas por el código, y resultan en " "mensajes de error como los mostrados aquí::" #: ../Doc/tutorial/errors.rst:58 msgid "" "The last line of the error message indicates what happened. Exceptions come " "in different types, and the type is printed as part of the message: the " "types in the example are :exc:`ZeroDivisionError`, :exc:`NameError` and :exc:" "`TypeError`. The string printed as the exception type is the name of the " "built-in exception that occurred. This is true for all built-in exceptions, " "but need not be true for user-defined exceptions (although it is a useful " "convention). Standard exception names are built-in identifiers (not reserved " "keywords)." msgstr "" "La última línea de los mensajes de error indica qué ha sucedido. Hay " "excepciones de diferentes tipos, y el tipo se imprime como parte del " "mensaje: los tipos en el ejemplo son: :exc:`ZeroDivisionError`, :exc:" "`NameError` y :exc:`TypeError`. La cadena mostrada como tipo de la " "excepción es el nombre de la excepción predefinida que ha ocurrido. Esto es " "válido para todas las excepciones predefinidas del intérprete, pero no tiene " "por que ser así para excepciones definidas por el usuario (aunque es una " "convención útil). Los nombres de las excepciones estándar son " "identificadores incorporados al intérprete (no son palabras clave " "reservadas)." #: ../Doc/tutorial/errors.rst:66 msgid "" "The rest of the line provides detail based on the type of exception and what " "caused it." msgstr "" "El resto de la línea provee información basado en el tipo de la excepción y " "qué la causó." #: ../Doc/tutorial/errors.rst:69 msgid "" "The preceding part of the error message shows the context where the " "exception occurred, in the form of a stack traceback. In general it contains " "a stack traceback listing source lines; however, it will not display lines " "read from standard input." msgstr "" "La parte anterior del mensaje de error muestra el contexto donde ocurrió la " "excepción, en forma de seguimiento de pila. En general, contiene un " "seguimiento de pila que enumera las líneas de origen; sin embargo, no " "mostrará las líneas leídas desde la entrada estándar." #: ../Doc/tutorial/errors.rst:74 msgid "" ":ref:`bltin-exceptions` lists the built-in exceptions and their meanings." msgstr "" ":ref:`bltin-exceptions` lista las excepciones predefinidas y sus " "significados." #: ../Doc/tutorial/errors.rst:80 msgid "Handling Exceptions" msgstr "Gestionando excepciones" #: ../Doc/tutorial/errors.rst:82 msgid "" "It is possible to write programs that handle selected exceptions. Look at " "the following example, which asks the user for input until a valid integer " "has been entered, but allows the user to interrupt the program (using :kbd:" "`Control-C` or whatever the operating system supports); note that a user-" "generated interruption is signalled by raising the :exc:`KeyboardInterrupt` " "exception. ::" msgstr "" "Es posible escribir programas que gestionen determinadas excepciones. Véase " "el siguiente ejemplo, que le pide al usuario una entrada hasta que ingrese " "un entero válido, pero permite al usuario interrumpir el programa (usando :" "kbd:`Control-C` o lo que soporte el sistema operativo); nótese que una " "interrupción generada por el usuario es señalizada generando la excepción :" "exc:`KeyboardInterrupt`. ::" #: ../Doc/tutorial/errors.rst:96 msgid "The :keyword:`try` statement works as follows." msgstr "La sentencia :keyword:`try` funciona de la siguiente manera." #: ../Doc/tutorial/errors.rst:98 msgid "" "First, the *try clause* (the statement(s) between the :keyword:`try` and :" "keyword:`except` keywords) is executed." msgstr "" "Primero, se ejecuta la cláusula *try* (la(s) linea(s) entre las palabras " "reservadas :keyword:`try` y la :keyword:`except`)." #: ../Doc/tutorial/errors.rst:101 msgid "" "If no exception occurs, the *except clause* is skipped and execution of the :" "keyword:`try` statement is finished." msgstr "" "Si no ocurre ninguna excepción, la cláusula *except* se omite y la ejecución " "de la cláusula :keyword:`try` finaliza." #: ../Doc/tutorial/errors.rst:104 msgid "" "If an exception occurs during execution of the :keyword:`try` clause, the " "rest of the clause is skipped. Then, if its type matches the exception " "named after the :keyword:`except` keyword, the *except clause* is executed, " "and then execution continues after the try/except block." msgstr "" "Si ocurre una excepción durante la ejecución de la cláusula :keyword:`try`, " "se omite el resto de la cláusula. Luego, si su tipo coincide con la " "excepción nombrada después de la palabra clave :keyword:`except`, se ejecuta " "la *cláusula except*, y luego la ejecución continúa después del bloque try/" "except." #: ../Doc/tutorial/errors.rst:109 msgid "" "If an exception occurs which does not match the exception named in the " "*except clause*, it is passed on to outer :keyword:`try` statements; if no " "handler is found, it is an *unhandled exception* and execution stops with a " "message as shown above." msgstr "" "Si ocurre una excepción que no coincide con la indicada en la *cláusula " "except* se pasa a los :keyword:`try` más externos; si no se encuentra un " "gestor, se genera una *unhandled exception* (excepción no gestionada) y la " "ejecución se interrumpe con un mensaje como el que se muestra arriba." #: ../Doc/tutorial/errors.rst:114 msgid "" "A :keyword:`try` statement may have more than one *except clause*, to " "specify handlers for different exceptions. At most one handler will be " "executed. Handlers only handle exceptions that occur in the corresponding " "*try clause*, not in other handlers of the same :keyword:`!try` statement. " "An *except clause* may name multiple exceptions as a parenthesized tuple, " "for example::" msgstr "" "Una declaración :keyword:`try` puede tener más de una *cláusula except*, " "para especificar gestores para diferentes excepciones. Como máximo, se " "ejecutará un gestor. Los gestores solo manejan las excepciones que ocurren " "en la *cláusula try* correspondiente, no en otros gestores de la misma " "declaración :keyword:`!try`. Una *cláusula except* puede nombrar múltiples " "excepciones como una tupla entre paréntesis, por ejemplo:" #: ../Doc/tutorial/errors.rst:123 msgid "" "A class in an :keyword:`except` clause is compatible with an exception if it " "is the same class or a base class thereof (but not the other way around --- " "an *except clause* listing a derived class is not compatible with a base " "class). For example, the following code will print B, C, D in that order::" msgstr "" "Una clase en una cláusula :keyword:`except` es compatible con una excepción " "si es de la misma clase o de una clase derivada de la misma (pero no de la " "otra manera --- una *cláusula except* listando una clase derivada no es " "compatible con una clase base). Por ejemplo, el siguiente código imprimirá " "B, C y D, en ese orden::" #: ../Doc/tutorial/errors.rst:147 msgid "" "Note that if the *except clauses* were reversed (with ``except B`` first), " "it would have printed B, B, B --- the first matching *except clause* is " "triggered." msgstr "" "Nótese que si las *cláusulas except* estuvieran invertidas (con ``except B`` " "primero), habría impreso B, B, B --- se usa la primera *cláusula except* " "coincidente." #: ../Doc/tutorial/errors.rst:150 msgid "" "When an exception occurs, it may have associated values, also known as the " "exception's *arguments*. The presence and types of the arguments depend on " "the exception type." msgstr "" "Cuando ocurre una excepción, puede tener un valor asociado, también conocido " "como el *argumento* de la excepción. La presencia y el tipo de argumento " "depende del tipo de excepción." #: ../Doc/tutorial/errors.rst:154 msgid "" "The *except clause* may specify a variable after the exception name. The " "variable is bound to the exception instance which typically has an ``args`` " "attribute that stores the arguments. For convenience, builtin exception " "types define :meth:`~object.__str__` to print all the arguments without " "explicitly accessing ``.args``. ::" msgstr "" "La *cláusula except* puede especificar una variable después del nombre de la " "excepción. La variable está ligada a la instancia de la excepción, que " "normalmente tiene un atributo ``args`` que almacena los argumentos. Por " "conveniencia, los tipos de excepción incorporados definen :meth:`~object." "__str__` para imprimir todos los argumentos sin acceder explícitamente a ``." "args``. ::" # No estoy seguro si es la mejor traducción. #: ../Doc/tutorial/errors.rst:177 msgid "" "The exception's :meth:`~object.__str__` output is printed as the last part " "('detail') of the message for unhandled exceptions." msgstr "" "La salida :meth:`~object.__str__` de la excepción se imprime como la última " "parte ('detalle') del mensaje para las excepciones no gestionadas." #: ../Doc/tutorial/errors.rst:180 msgid "" ":exc:`BaseException` is the common base class of all exceptions. One of its " "subclasses, :exc:`Exception`, is the base class of all the non-fatal " "exceptions. Exceptions which are not subclasses of :exc:`Exception` are not " "typically handled, because they are used to indicate that the program should " "terminate. They include :exc:`SystemExit` which is raised by :meth:`sys." "exit` and :exc:`KeyboardInterrupt` which is raised when a user wishes to " "interrupt the program." msgstr "" ":exc:`BaseException` es la clase base común de todas las excepciones. Una de " "sus subclases, :exc:`Exception`, es la clase base de todas las excepciones " "no fatales. Las excepciones que no son subclases de :exc:`Exception` no se " "suelen manejar, porque se utilizan para indicar que el programa debe " "terminar. Entre ellas se incluyen :exc:`SystemExit`, que es lanzada por :" "meth:`sys.exit` y :exc:`KeyboardInterrupt`, que se lanza cuando un usuario " "desea interrumpir el programa." #: ../Doc/tutorial/errors.rst:188 msgid "" ":exc:`Exception` can be used as a wildcard that catches (almost) everything. " "However, it is good practice to be as specific as possible with the types of " "exceptions that we intend to handle, and to allow any unexpected exceptions " "to propagate on." msgstr "" ":exc:`Exception` se puede utilizar como un comodín que atrapa (casi) todo. " "Sin embargo, es una buena práctica ser lo más específico posible con los " "tipos de excepciones que pretendemos manejar, y permitir que cualquier " "excepción inesperada se propague." #: ../Doc/tutorial/errors.rst:193 msgid "" "The most common pattern for handling :exc:`Exception` is to print or log the " "exception and then re-raise it (allowing a caller to handle the exception as " "well)::" msgstr "" "El patrón más común para gestionar :exc:`Exception` es imprimir o registrar " "la excepción y luego volver a re-lanzarla (permitiendo a un llamador manejar " "la excepción también)::" #: ../Doc/tutorial/errors.rst:211 msgid "" "The :keyword:`try` ... :keyword:`except` statement has an optional *else " "clause*, which, when present, must follow all *except clauses*. It is " "useful for code that must be executed if the *try clause* does not raise an " "exception. For example::" msgstr "" "La declaración :keyword:`try` ... :keyword:`except` tiene una *cláusula " "else* opcional, que, cuando está presente, debe seguir todas las *cláusulas " "except*. Es útil para el código que debe ejecutarse si la *cláusula try* no " "lanza una excepción. Por ejemplo::" #: ../Doc/tutorial/errors.rst:225 msgid "" "The use of the :keyword:`!else` clause is better than adding additional code " "to the :keyword:`try` clause because it avoids accidentally catching an " "exception that wasn't raised by the code being protected by the :keyword:`!" "try` ... :keyword:`!except` statement." msgstr "" "El uso de la cláusula :keyword:`!else` es mejor que agregar código adicional " "en la cláusula :keyword:`try` porque evita capturar accidentalmente una " "excepción que no fue generada por el código que está protegido por la " "declaración :keyword:`!try` ... :keyword:`!except`." #: ../Doc/tutorial/errors.rst:230 msgid "" "Exception handlers do not handle only exceptions that occur immediately in " "the *try clause*, but also those that occur inside functions that are called " "(even indirectly) in the *try clause*. For example::" msgstr "" "Los gestores de excepciones no sólo gestionan excepciones que ocurren " "inmediatamente en la *cláusula try*, sino también aquellas que ocurren " "dentro de funciones que son llamadas (incluso indirectamente) en la " "*cláusula try*. Por ejemplo::" #: ../Doc/tutorial/errors.rst:248 msgid "Raising Exceptions" msgstr "Lanzando excepciones" #: ../Doc/tutorial/errors.rst:250 msgid "" "The :keyword:`raise` statement allows the programmer to force a specified " "exception to occur. For example::" msgstr "" "La declaración :keyword:`raise` permite al programador forzar a que ocurra " "una excepción específica. Por ejemplo::" #: ../Doc/tutorial/errors.rst:258 msgid "" "The sole argument to :keyword:`raise` indicates the exception to be raised. " "This must be either an exception instance or an exception class (a class " "that derives from :class:`BaseException`, such as :exc:`Exception` or one of " "its subclasses). If an exception class is passed, it will be implicitly " "instantiated by calling its constructor with no arguments::" msgstr "" "El único argumento de :keyword:`raise` indica la excepción a lanzar. Debe " "ser una instancia de excepción o una clase de excepción (una clase que " "derive de :class:`BaseException`, como :exc:`Exception` o una de sus " "subclases). Si se pasa una clase de excepción, se instanciará implícitamente " "llamando a su constructor sin argumentos::" #: ../Doc/tutorial/errors.rst:266 msgid "" "If you need to determine whether an exception was raised but don't intend to " "handle it, a simpler form of the :keyword:`raise` statement allows you to re-" "raise the exception::" msgstr "" "Si es necesario determinar si una excepción fue lanzada pero sin intención " "de gestionarla, una versión simplificada de la instrucción :keyword:`raise` " "te permite relanzarla::" #: ../Doc/tutorial/errors.rst:285 msgid "Exception Chaining" msgstr "Encadenamiento de excepciones" #: ../Doc/tutorial/errors.rst:287 msgid "" "If an unhandled exception occurs inside an :keyword:`except` section, it " "will have the exception being handled attached to it and included in the " "error message::" msgstr "" "Si se produce una excepción no gestionada dentro de una sección :keyword:" "`except`, se le adjuntará la excepción que se está gestionando y se incluirá " "en el mensaje de error::" #: ../Doc/tutorial/errors.rst:306 msgid "" "To indicate that an exception is a direct consequence of another, the :" "keyword:`raise` statement allows an optional :keyword:`from` clause::" msgstr "" "Para indicar que una excepción es consecuencia directa de otra, la " "sentencia :keyword:`raise` permite una cláusula opcional :keyword:" "`from`::" #: ../Doc/tutorial/errors.rst:312 msgid "This can be useful when you are transforming exceptions. For example::" msgstr "" "Esto puede resultar útil cuando está transformando excepciones. Por ejemplo::" #: ../Doc/tutorial/errors.rst:333 msgid "" "It also allows disabling automatic exception chaining using the ``from " "None`` idiom::" msgstr "" "También permite deshabilitar el encadenamiento automático de excepciones " "utilizando el modismo ``from None``::" #: ../Doc/tutorial/errors.rst:345 msgid "" "For more information about chaining mechanics, see :ref:`bltin-exceptions`." msgstr "" "Para obtener más información sobre la mecánica del encadenamiento, consulte :" "ref:`bltin-exceptions`." #: ../Doc/tutorial/errors.rst:351 msgid "User-defined Exceptions" msgstr "Excepciones definidas por el usuario" #: ../Doc/tutorial/errors.rst:353 msgid "" "Programs may name their own exceptions by creating a new exception class " "(see :ref:`tut-classes` for more about Python classes). Exceptions should " "typically be derived from the :exc:`Exception` class, either directly or " "indirectly." msgstr "" "Los programas pueden nombrar sus propias excepciones creando una nueva clase " "excepción (mirá :ref:`tut-classes` para más información sobre las clases de " "Python). Las excepciones, típicamente, deberán derivar de la clase :exc:" "`Exception`, directa o indirectamente." #: ../Doc/tutorial/errors.rst:357 msgid "" "Exception classes can be defined which do anything any other class can do, " "but are usually kept simple, often only offering a number of attributes that " "allow information about the error to be extracted by handlers for the " "exception." msgstr "" "Las clases de Excepción pueden ser definidas de la misma forma que cualquier " "otra clase, pero es habitual mantenerlas lo más simples posible, a menudo " "ofreciendo solo un número de atributos con información sobre el error que " "leerán los gestores de la excepción." #: ../Doc/tutorial/errors.rst:361 msgid "" "Most exceptions are defined with names that end in \"Error\", similar to the " "naming of the standard exceptions." msgstr "" "La mayoría de las excepciones se definen con nombres acabados en \"Error\", " "de manera similar a la nomenclatura de las excepciones estándar." #: ../Doc/tutorial/errors.rst:364 msgid "" "Many standard modules define their own exceptions to report errors that may " "occur in functions they define." msgstr "" "Muchos módulos estándar definen sus propias excepciones para reportar " "errores que pueden ocurrir en funciones propias." #: ../Doc/tutorial/errors.rst:371 msgid "Defining Clean-up Actions" msgstr "Definiendo acciones de limpieza" #: ../Doc/tutorial/errors.rst:373 msgid "" "The :keyword:`try` statement has another optional clause which is intended " "to define clean-up actions that must be executed under all circumstances. " "For example::" msgstr "" "La declaración :keyword:`try` tiene otra cláusula opcional cuyo propósito es " "definir acciones de limpieza que serán ejecutadas bajo ciertas " "circunstancias. Por ejemplo::" #: ../Doc/tutorial/errors.rst:387 msgid "" "If a :keyword:`finally` clause is present, the :keyword:`!finally` clause " "will execute as the last task before the :keyword:`try` statement completes. " "The :keyword:`!finally` clause runs whether or not the :keyword:`!try` " "statement produces an exception. The following points discuss more complex " "cases when an exception occurs:" msgstr "" "Si una cláusula :keyword:`finally` está presente, el bloque :keyword:`!" "finally` se ejecutará al final antes de que todo el bloque :keyword:`try` se " "complete. La cláusula :keyword:`!finally` se ejecuta independientemente de " "que la cláusula :keyword:`!try` produzca o no una excepción. Los siguientes " "puntos explican casos más complejos en los que se produce una excepción:" #: ../Doc/tutorial/errors.rst:393 msgid "" "If an exception occurs during execution of the :keyword:`!try` clause, the " "exception may be handled by an :keyword:`except` clause. If the exception is " "not handled by an :keyword:`!except` clause, the exception is re-raised " "after the :keyword:`!finally` clause has been executed." msgstr "" "Si ocurre una excepción durante la ejecución de la cláusula :keyword:`!try`, " "la excepción podría ser gestionada por una cláusula :keyword:`except`. Si la " "excepción no es gestionada por una cláusula :keyword:`!except`, la excepción " "es relanzada después de que se ejecute el bloque de la cláusula :keyword:`!" "finally`." #: ../Doc/tutorial/errors.rst:399 msgid "" "An exception could occur during execution of an :keyword:`!except` or :" "keyword:`!else` clause. Again, the exception is re-raised after the :keyword:" "`!finally` clause has been executed." msgstr "" "Podría aparecer una excepción durante la ejecución de una cláusula :keyword:" "`!except` o :keyword:`!else`. De nuevo, la excepción será relanzada después " "de que el bloque de la cláusula :keyword:`!finally` se ejecute." #: ../Doc/tutorial/errors.rst:403 msgid "" "If the :keyword:`!finally` clause executes a :keyword:`break`, :keyword:" "`continue` or :keyword:`return` statement, exceptions are not re-raised." msgstr "" "Si la cláusula :keyword:`!finally` ejecuta una declaración :keyword:" "`break`, :keyword:`continue` o :keyword:`return`, las excepciones no se " "vuelven a lanzar." #: ../Doc/tutorial/errors.rst:407 msgid "" "If the :keyword:`!try` statement reaches a :keyword:`break`, :keyword:" "`continue` or :keyword:`return` statement, the :keyword:`!finally` clause " "will execute just prior to the :keyword:`!break`, :keyword:`!continue` or :" "keyword:`!return` statement's execution." msgstr "" "Si el bloque :keyword:`!try` llega a una sentencia :keyword:`break`, :" "keyword:`continue` o :keyword:`return`, la cláusula :keyword:`!finally` se " "ejecutará justo antes de la ejecución de dicha sentencia." #: ../Doc/tutorial/errors.rst:413 msgid "" "If a :keyword:`!finally` clause includes a :keyword:`!return` statement, the " "returned value will be the one from the :keyword:`!finally` clause's :" "keyword:`!return` statement, not the value from the :keyword:`!try` " "clause's :keyword:`!return` statement." msgstr "" "Si una cláusula :keyword:`!finally` incluye una sentencia :keyword:`!" "return`, el valor retornado será el de la cláusula :keyword:`!finally`, no " "la del de la sentencia :keyword:`!return` de la cláusula :keyword:`!try`." #: ../Doc/tutorial/errors.rst:419 msgid "For example::" msgstr "Por ejemplo::" #: ../Doc/tutorial/errors.rst:430 msgid "A more complicated example::" msgstr "Un ejemplo más complicado::" #: ../Doc/tutorial/errors.rst:455 msgid "" "As you can see, the :keyword:`finally` clause is executed in any event. " "The :exc:`TypeError` raised by dividing two strings is not handled by the :" "keyword:`except` clause and therefore re-raised after the :keyword:`!" "finally` clause has been executed." msgstr "" "Como se puede ver, la cláusula :keyword:`finally` siempre se ejecuta. La " "excepción :exc:`TypeError` lanzada al dividir dos cadenas de texto no es " "gestionado por la cláusula :keyword:`except` y por lo tanto es relanzada " "luego de que se ejecuta la cláusula :keyword:`!finally`." #: ../Doc/tutorial/errors.rst:460 msgid "" "In real world applications, the :keyword:`finally` clause is useful for " "releasing external resources (such as files or network connections), " "regardless of whether the use of the resource was successful." msgstr "" "En aplicaciones reales, la cláusula :keyword:`finally` es útil para liberar " "recursos externos (como archivos o conexiones de red), sin importar si el " "uso del recurso fue exitoso." #: ../Doc/tutorial/errors.rst:468 msgid "Predefined Clean-up Actions" msgstr "Acciones predefinidas de limpieza" #: ../Doc/tutorial/errors.rst:470 msgid "" "Some objects define standard clean-up actions to be undertaken when the " "object is no longer needed, regardless of whether or not the operation using " "the object succeeded or failed. Look at the following example, which tries " "to open a file and print its contents to the screen. ::" msgstr "" "Algunos objetos definen acciones de limpieza estándar para llevar a cabo " "cuando el objeto ya no necesario, independientemente de que las operaciones " "sobre el objeto hayan sido exitosas o no. Véase el siguiente ejemplo, que " "intenta abrir un archivo e imprimir su contenido en la pantalla. ::" #: ../Doc/tutorial/errors.rst:478 msgid "" "The problem with this code is that it leaves the file open for an " "indeterminate amount of time after this part of the code has finished " "executing. This is not an issue in simple scripts, but can be a problem for " "larger applications. The :keyword:`with` statement allows objects like files " "to be used in a way that ensures they are always cleaned up promptly and " "correctly. ::" msgstr "" "El problema con este código es que deja el archivo abierto por un periodo de " "tiempo indeterminado luego de que esta parte termine de ejecutarse. Esto no " "es un problema en *scripts* simples, pero puede ser un problema en " "aplicaciones más grandes. La declaración :keyword:`with` permite que los " "objetos como archivos sean usados de una forma que asegure que siempre se " "los libera rápido y en forma correcta.::" #: ../Doc/tutorial/errors.rst:488 msgid "" "After the statement is executed, the file *f* is always closed, even if a " "problem was encountered while processing the lines. Objects which, like " "files, provide predefined clean-up actions will indicate this in their " "documentation." msgstr "" "Una vez que la declaración se ejecuta, el fichero *f* siempre se cierra, " "incluso si aparece algún error durante el procesado de las líneas. Los " "objetos que, como los ficheros, posean acciones predefinidas de limpieza lo " "indicarán en su documentación." #: ../Doc/tutorial/errors.rst:496 msgid "Raising and Handling Multiple Unrelated Exceptions" msgstr "Lanzando y gestionando múltiples excepciones no relacionadas" #: ../Doc/tutorial/errors.rst:498 msgid "" "There are situations where it is necessary to report several exceptions that " "have occurred. This is often the case in concurrency frameworks, when " "several tasks may have failed in parallel, but there are also other use " "cases where it is desirable to continue execution and collect multiple " "errors rather than raise the first exception." msgstr "" "Hay situaciones en las que es necesario informar de varias excepciones que " "se han producido. Este es a menudo el caso en los marcos de concurrencia, " "cuando varias tareas pueden haber fallado en paralelo, pero también hay " "otros casos de uso en los que es deseable continuar la ejecución y recoger " "múltiples errores en lugar de lanzar la primera excepción." #: ../Doc/tutorial/errors.rst:504 msgid "" "The builtin :exc:`ExceptionGroup` wraps a list of exception instances so " "that they can be raised together. It is an exception itself, so it can be " "caught like any other exception. ::" msgstr "" "El incorporado :exc:`ExceptionGroup` envuelve una lista de instancias de " "excepción para que puedan ser lanzadas juntas. Es una excepción en sí misma, " "por lo que puede capturarse como cualquier otra excepción. ::" #: ../Doc/tutorial/errors.rst:530 msgid "" "By using ``except*`` instead of ``except``, we can selectively handle only " "the exceptions in the group that match a certain type. In the following " "example, which shows a nested exception group, each ``except*`` clause " "extracts from the group exceptions of a certain type while letting all other " "exceptions propagate to other clauses and eventually to be reraised. ::" msgstr "" "Utilizando ``except*`` en lugar de ``except``, podemos manejar " "selectivamente sólo las excepciones del grupo que coincidan con un " "determinado tipo. En el siguiente ejemplo, que muestra un grupo de " "excepciones anidado, cada cláusula ``except*`` extrae del grupo las " "excepciones de un tipo determinado, mientras que deja que el resto de " "excepciones se propaguen a otras cláusulas y, finalmente, se vuelvan a " "lanzar. ::" #: ../Doc/tutorial/errors.rst:573 msgid "" "Note that the exceptions nested in an exception group must be instances, not " "types. This is because in practice the exceptions would typically be ones " "that have already been raised and caught by the program, along the following " "pattern::" msgstr "" "Tenga en cuenta que las excepciones anidadas en un grupo de excepciones " "deben ser instancias, no tipos. Esto se debe a que en la práctica las " "excepciones serían típicamente las que ya han sido planteadas y capturadas " "por el programa, siguiendo el siguiente patrón::" #: ../Doc/tutorial/errors.rst:593 msgid "Enriching Exceptions with Notes" msgstr "Enriqueciendo excepciones con notas" #: ../Doc/tutorial/errors.rst:595 msgid "" "When an exception is created in order to be raised, it is usually " "initialized with information that describes the error that has occurred. " "There are cases where it is useful to add information after the exception " "was caught. For this purpose, exceptions have a method ``add_note(note)`` " "that accepts a string and adds it to the exception's notes list. The " "standard traceback rendering includes all notes, in the order they were " "added, after the exception. ::" msgstr "" "Cuando se crea una excepción para ser lanzada, normalmente se inicializa con " "información que describe el error que se ha producido. Hay casos en los que " "es útil añadir información después de que la excepción haya sido capturada. " "Para este propósito, las excepciones tienen un método ``add_note(note)`` que " "acepta una cadena y la añade a la lista de notas de la excepción. La " "representación estándar del rastreo incluye todas las notas, en el orden en " "que fueron añadidas, después de la excepción. ::" #: ../Doc/tutorial/errors.rst:616 msgid "" "For example, when collecting exceptions into an exception group, we may want " "to add context information for the individual errors. In the following each " "exception in the group has a note indicating when this error has occurred. ::" msgstr "" "Por ejemplo, al recopilar excepciones en un grupo de excepciones, es posible " "que queramos añadir información de contexto para los errores individuales. A " "continuación, cada excepción del grupo tiene una nota que indica cuándo se " "ha producido ese error. ::"