Changeset 45
- Timestamp:
- 05/07/09 09:13:27 (4 years ago)
- File:
-
- 1 edited
-
trunk/traducidos/errors.rst (modified) (5 diffs)
Legend:
- Unmodified
- Added
- Removed
-
trunk/traducidos/errors.rst
r4 r45 2 2 3 3 ********************* 4 Error s and Exceptions4 Errores y excepciones 5 5 ********************* 6 6 7 Until now error messages haven't been more than mentioned, but if you have tried 8 out the examples you have probably seen some. There are (at least) two 9 distinguishable kinds of errors: *syntax errors* and *exceptions*.7 Hasta ahora los mensajes de error no habían sido más que mencionados, pero si 8 intentaste los ejemplos probablemente hayas visto algunos. Hay (al menos) dos 9 tipos diferentes de errores: *errores de sintaxis* y *excepciones*. 10 10 11 11 12 12 .. _tut-syntaxerrors: 13 13 14 Syntax Errors 15 ============= 16 17 Syntax errors, also known as parsing errors, are perhaps the most common kind of 18 complaint you get while you are still learning Python:: 19 20 >>> while True print 'Hello world' 21 File "<stdin>", line 1, in ? 22 while True print 'Hello world' 14 Errores de sintaxis 15 =================== 16 17 Los errores de sintaxis, también conocidos como errores de interpretación, son 18 quizás el tipo de queja más común que tenés cuando todavía estás aprendiendo 19 Python:: 20 21 >>> while True print 'Hola mundo' 22 File "<stdin>", line 1, in ? 23 while True print 'Hola mundo' 23 24 ^ 24 25 SyntaxError: invalid syntax 25 26 26 The parser repeats the offending line and displays a little 'arrow' pointing at 27 the earliest point in the line where the error was detected. The error is 28 caused by (or at least detected at) the token *preceding* the arrow: in the 29 e xample, the error is detected at the keyword :keyword:`print`, since a colon30 (``':'``) is missing before it. File name and line number are printed so you 31 know where to look in case the input came from a script.27 El intérprete repite la linea culpable y muestra una pequeña 'flecha' 28 que apunta al primer lugar donde se detectó el error. Este es causado por (o 29 al menos detectado en) el símbolo que *precede* a la flecha: en el ejemplo, 30 el error se detecta en el :keyword:`print`, ya que faltan dos puntos (``':'``) 31 antes del mismo. Se muestran el nombre del archivo y el número de linea para 32 que sepas dónde mirar en caso de que la entrada venga de un programa. 32 33 33 34 34 35 .. _tut-exceptions: 35 36 36 Exceptions 37 ========== 38 39 Even if a statement or expression is syntactically correct, it may cause an 40 error when an attempt is made to execute it. Errors detected during execution 41 are called *exceptions* and are not unconditionally fatal: you will soon learn 42 how to handle them in Python programs. Most exceptions are not handled by 43 programs, however, and result in error messages as shown here:: 37 Excepciones 38 =========== 39 40 Incluso si la declaración o expresión es sintácticamente correcta, puede 41 generar un error cuando se intenta ejecutarla. Los errores detectados durante 42 la ejecución se llaman *excepciones*, y no son incondicionalmente fatales: 43 pronto aprenderás cómo manejarlos en los programas en Python. Sin embargo, la 44 mayoría de las excepciones no son manejadas por los programas, y resultan en 45 mensajes de error como los mostrados aquí:: 44 46 45 47 >>> 10 * (1/0) … … 56 58 TypeError: cannot concatenate 'str' and 'int' objects 57 59 58 The last line of the error message indicates what happened. Exceptions come in 59 different types, and the type is printed as part of the message: the types in 60 the example are :exc:`ZeroDivisionError`, :exc:`NameError` and :exc:`TypeError`. 61 The string printed as the exception type is the name of the built-in exception 62 that occurred. This is true for all built-in exceptions, but need not be true 63 for user-defined exceptions (although it is a useful convention). Standard 64 exception names are built-in identifiers (not reserved keywords). 65 66 The rest of the line provides detail based on the type of exception and what 67 caused it. 68 69 The preceding part of the error message shows the context where the exception 70 happened, in the form of a stack traceback. In general it contains a stack 71 traceback listing source lines; however, it will not display lines read from 72 standard input. 73 74 :ref:`bltin-exceptions` lists the built-in exceptions and their meanings. 60 La última linea de los mensajes de error indica qué sucedió. Las excepciones 61 vienen de distintos tipos, y el tipo se imprime como parte del mensaje: los 62 tipos en el ejemplo son: :exc:`ZeroDivisionError`, :exc:`NameError` y 63 :exc:`TypeError`. La cadena mostrada como tipo de la excepción es el nombre de 64 la excepción integrada que ocurrió. Esto es verdad para todas las excepciones 65 integradas al intérprete, pero no necesita ser verdad para excepciones 66 definidas por el usuario (aunque es una convención útil). Los nombres de las 67 excepciones estándar son identificadores integrados al intérprete (no son 68 palabras clave reservadas). 69 70 El resto de la linea provee un detalle basado en el tipo de la excepción y qué 71 la causó. 72 73 La parte anterior del mensaje de error muestra el contexto donde la excepción 74 sucedió, en la forma de un ***stack traceback*** listando lineas fuente; sin 75 embargo, no mostrará lineas leídas de la entrada estándar. 76 77 :ref:`bltin-exceptions` lista las excepciones integradas y sus significados. 75 78 76 79 77 80 .. _tut-handling: 78 81 79 Handling Exceptions 80 =================== 81 82 It is possible to write programs that handle selected exceptions. Look at the 83 following example, which asks the user for input until a valid integer has been 84 entered, but allows the user to interrupt the program (using :kbd:`Control-C` or 85 whatever the operating system supports); note that a user-generated interruption 86 is signalled by raising the :exc:`KeyboardInterrupt` exception. :: 82 Manejando excepciones 83 ===================== 84 85 Es posible escribir programas que manejen las excepciones que quiera. Mirá el 86 siguiente ejemplo, que le pide al usuario una entrada hasta que ingrese un 87 entero válido, pero permite al usuario interrumpir el programa (usando 88 :kbd:`Control-C` o lo que sea que el sistema operativo soporte); notá que una 89 interrupción generada por el usuario se señaliza generando la excepción 90 :exc:`KeyboardInterrupt`. :: 87 91 88 92 >>> while True: 89 93 ... try: 90 ... x = int(raw_input( "Please enter a number: "))94 ... x = int(raw_input(u"Por favor ingrese un número: ")) 91 95 ... break 92 96 ... except ValueError: 93 ... print "Oops! That was no valid number. Try again..."94 ... 95 96 The :keyword:`try` statement works as follows. 97 98 * First, the *try clause* (the statement(s) between the :keyword:`try` and99 :keyword:` except` keywords) is executed.100 101 * If no exception occurs, the *except clause* is skipped and execution of the102 :keyword:`try` statement is finished.103 104 * If an exception occurs during execution of the try clause, the rest of the105 clause is skipped. Then if its type matches the exception named after the106 :keyword:`except` keyword, the except clause is executed, and then execution107 continues after the :keyword:`try` statement.108 109 * If an exception occurs which does not match the exception named in the except110 clause, it is passed on to outer :keyword:`try` statements; if no handler is111 found, it is an *unhandled exception* and execution stops with a message as112 shown above.97 ... print u"Oops! No era válido. Intente nuevamente..." 98 ... 99 100 La declaración :keyword:`try` funciona de la siguiente manera: 101 102 * Primero, se ejecuta el *bloque try* (el código entre las declaraciones 103 :keyword:`try` y :keyword:`except`). 104 105 * Si no ocurre ninguna excepción, el *bloque except* se saltea y termina la 106 ejecución de la declaración :keyword:`try`. 107 108 * Si ocurre una excepción durante la ejecución del *bloque try*, el resto del 109 bloque se saltea. Luego, si su tipo coincide con la excepción nombrada luego 110 del :keyword:`except`, se ejecuta el *bloque except*, y la ejecución continúa 111 luego de la declaración :keyword:`try`. 112 113 * Si ocurre una excepción que no coincide con la excepción nombrada en el 114 :keyword:`except`, esta se pasa a declaraciones :keyword:`try` de más afuera; 115 si no se encuentra a nada que la maneje, es una *excepción no manejada*, y la 116 ejecución se frena con un mensaje como los mostrado arriba. 113 117 114 118 A :keyword:`try` statement may have more than one except clause, to specify … … 200 204 >>> def this_fails(): 201 205 ... x = 1/0 202 ... 206 ... 203 207 >>> try: 204 208 ... this_fails() 205 209 ... except ZeroDivisionError as detail: 206 210 ... print 'Handling run-time error:', detail 207 ... 211 ... 208 212 Handling run-time error: integer division or modulo by zero 209 213 … … 257 261 ... def __str__(self): 258 262 ... return repr(self.value) 259 ... 263 ... 260 264 >>> try: 261 265 ... raise MyError(2*2) 262 266 ... except MyError as e: 263 267 ... print 'My exception occurred, value:', e.value 264 ... 268 ... 265 269 My exception occurred, value: 4 266 270 >>> raise MyError, 'oops!' … … 332 336 ... finally: 333 337 ... print 'Goodbye, world!' 334 ... 338 ... 335 339 Goodbye, world! 336 340 Traceback (most recent call last):
Note: See TracChangeset
for help on using the changeset viewer.
![(please configure the [header_logo] section in trac.ini)](/python-tutorial/chrome/site/your_project_logo.png)