Changeset 45


Ignore:
Timestamp:
05/07/09 09:13:27 (4 years ago)
Author:
facundobatista
Message:

Errores!

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/traducidos/errors.rst

    r4 r45  
    22 
    33********************* 
    4 Errors and Exceptions 
     4Errores y excepciones 
    55********************* 
    66 
    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*. 
     7Hasta ahora los mensajes de error no habían sido más que mencionados, pero si 
     8intentaste los ejemplos probablemente hayas visto algunos.  Hay (al menos) dos 
     9tipos diferentes de errores: *errores de sintaxis* y *excepciones*. 
    1010 
    1111 
    1212.. _tut-syntaxerrors: 
    1313 
    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' 
     14Errores de sintaxis 
     15=================== 
     16 
     17Los errores de sintaxis, también conocidos como errores de interpretación, son 
     18quizás el tipo de queja más común que tenés cuando todavía estás aprendiendo 
     19Python:: 
     20 
     21   >>> while True print 'Hola mundo' 
     22     File "<stdin>", line 1, in ? 
     23       while True print 'Hola mundo' 
    2324                      ^ 
    2425   SyntaxError: invalid syntax 
    2526 
    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 example, the error is detected at the keyword :keyword:`print`, since a colon 
    30 (``':'``) 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. 
     27El intérprete repite la linea culpable y muestra una pequeña 'flecha' 
     28que apunta al primer lugar donde se detectó el error.  Este es causado por (o 
     29al menos detectado en) el símbolo que *precede* a la flecha: en el ejemplo, 
     30el error se detecta en el :keyword:`print`, ya que faltan dos puntos (``':'``) 
     31antes del mismo.  Se muestran el nombre del archivo y el número de linea para 
     32que sepas dónde mirar en caso de que la entrada venga de un programa. 
    3233 
    3334 
    3435.. _tut-exceptions: 
    3536 
    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:: 
     37Excepciones 
     38=========== 
     39 
     40Incluso si la declaración o expresión es sintácticamente correcta, puede 
     41generar un error cuando se intenta ejecutarla.  Los errores detectados durante 
     42la ejecución se llaman *excepciones*, y no son incondicionalmente fatales: 
     43pronto aprenderás cómo manejarlos en los programas en Python.  Sin embargo, la 
     44mayoría de las excepciones no son manejadas por los programas, y resultan en 
     45mensajes de error como los mostrados aquí:: 
    4446 
    4547   >>> 10 * (1/0) 
     
    5658   TypeError: cannot concatenate 'str' and 'int' objects 
    5759 
    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. 
     60La última linea de los mensajes de error indica qué sucedió.  Las excepciones 
     61vienen de distintos tipos, y el tipo se imprime como parte del mensaje: los 
     62tipos 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 
     64la excepción integrada que ocurrió.  Esto es verdad para todas las excepciones 
     65integradas al intérprete, pero no necesita ser verdad para excepciones 
     66definidas por el usuario (aunque es una convención útil).  Los nombres de las 
     67excepciones estándar son identificadores integrados al intérprete (no son 
     68palabras clave reservadas). 
     69 
     70El resto de la linea provee un detalle basado en el tipo de la excepción y qué 
     71la causó. 
     72 
     73La parte anterior del mensaje de error muestra el contexto donde la excepción 
     74sucedió, en la forma de un ***stack traceback*** listando lineas fuente; sin 
     75embargo, no mostrará lineas leídas de la entrada estándar. 
     76 
     77:ref:`bltin-exceptions` lista las excepciones integradas y sus significados. 
    7578 
    7679 
    7780.. _tut-handling: 
    7881 
    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. :: 
     82Manejando excepciones 
     83===================== 
     84 
     85Es posible escribir programas que manejen las excepciones que quiera.  Mirá el 
     86siguiente ejemplo, que le pide al usuario una entrada hasta que ingrese un 
     87entero 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 
     89interrupción generada por el usuario se señaliza generando la excepción 
     90:exc:`KeyboardInterrupt`. :: 
    8791 
    8892   >>> while True: 
    8993   ...     try: 
    90    ...         x = int(raw_input("Please enter a number: ")) 
     94   ...         x = int(raw_input(u"Por favor ingrese un número: ")) 
    9195   ...         break 
    9296   ...     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` and 
    99   :keyword:`except` keywords) is executed. 
    100  
    101 * If no exception occurs, the *except clause* is skipped and execution of the 
    102   :keyword:`try` statement is finished. 
    103  
    104 * If an exception occurs during execution of the try clause, the rest of the 
    105   clause is skipped.  Then if its type matches the exception named after the 
    106   :keyword:`except` keyword, the except clause is executed, and then execution 
    107   continues after the :keyword:`try` statement. 
    108  
    109 * If an exception occurs which does not match the exception named in the except 
    110   clause, it is passed on to outer :keyword:`try` statements; if no handler is 
    111   found, it is an *unhandled exception* and execution stops with a message as 
    112   shown above. 
     97   ...         print u"Oops!  No era válido.  Intente nuevamente..." 
     98   ... 
     99 
     100La 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. 
    113117 
    114118A :keyword:`try` statement may have more than one except clause, to specify 
     
    200204   >>> def this_fails(): 
    201205   ...     x = 1/0 
    202    ...  
     206   ... 
    203207   >>> try: 
    204208   ...     this_fails() 
    205209   ... except ZeroDivisionError as detail: 
    206210   ...     print 'Handling run-time error:', detail 
    207    ...  
     211   ... 
    208212   Handling run-time error: integer division or modulo by zero 
    209213 
     
    257261   ...     def __str__(self): 
    258262   ...         return repr(self.value) 
    259    ...  
     263   ... 
    260264   >>> try: 
    261265   ...     raise MyError(2*2) 
    262266   ... except MyError as e: 
    263267   ...     print 'My exception occurred, value:', e.value 
    264    ...  
     268   ... 
    265269   My exception occurred, value: 4 
    266270   >>> raise MyError, 'oops!' 
     
    332336   ... finally: 
    333337   ...     print 'Goodbye, world!' 
    334    ...  
     338   ... 
    335339   Goodbye, world! 
    336340   Traceback (most recent call last): 
Note: See TracChangeset for help on using the changeset viewer.