Exception handling · Manejo de excepciones
| English | Español |
|---|---|
| exception/ekˈsepʃn/ | excepción |
| exception handling/ekˈsepʃn ˈhændlɪŋ/ | manejo de excepciones |
| raise/reɪz/ | elevan |
The check that cannot be written
- A program opens a file. Before opening it, you could check that the file exists, that it is readable, that the disk is present. Suppose every check passes.
- Between the last check and the open, a user pulls out the USB stick. The file existed when you asked and does not exist when you open it, and no amount of checking in advance could have closed that gap.
- Some errors are simply not preventable, because the world changes between the test and the action. What a program can do is respond to them when they happen.
- This lesson is the exception 异常, the TRY structure that handles one, and where in a program an exception should be caught.
La comprobación que no se puede escribir
- Un programa abre un archivo. Antes de abrirlo, podrías comprobar que el archivo existe, que es legible y que la unidad de almacenamiento está presente. Supón que todas las comprobaciones tienen éxito.
- Entre la última comprobación y la apertura del archivo, un usuario extrae la memoria USB. El archivo existía cuando lo consultaste y no existe al intentar abrirlo; ninguna cantidad de comprobaciones previas podría haber eliminado esa brecha.
- Algunos errores simplemente no son prevenibles, porque el mundo cambia entre la prueba y la acción. Lo que un programa puede hacer es responder a ellos cuando ocurren.
- Esta lección trata sobre la excepción, la estructura TRY que la maneja y dónde en un programa debe capturarse una excepción.
What an exception is and why handle it
- An exception is an error that occurs during execution: division by zero, a file not found, invalid input, a network that has gone away.
- Exception handling 异常处理 lets the program detect the error and respond in a controlled way, instead of crashing and losing the user's work.
- Real programs face errors that cannot be prevented in advance, as the hook shows. And without exceptions, every single operation would need its own
IFcheck around it, burying the actual algorithm in error tests. - The third benefit is the one the exam most often asks for: it separates the normal flow from the error handling, so the main path reads cleanly.
Qué es una excepción y por qué manejarla
- Una excepción es un error que ocurre durante la ejecución: división por cero, archivo no encontrado, entrada inválida o red desconectada.
- El manejo de excepciones permite al programa detectar el error y responder de manera controlada, en lugar de colapsar y perder el trabajo del usuario.
- Los programas reales enfrentan errores que no pueden prevenirse con antelación, como muestra el gancho. Sin excepciones, cada operación necesitaría su propia comprobación
IFalrededor, enterrando el algoritmo real bajo pruebas de error. - El tercer beneficio es el que más suele preguntar el examen: separa el flujo normal del manejo de errores, manteniendo limpio el camino principal.
An exception is: · Una excepción es:
Exceptions are run-time problems (divide by zero, file not found) that handling lets you respond to gracefully. · Las excepciones son problemas en tiempo de ejecución (división por cero, archivo no encontrado) cuyo manejo permite responder de forma adecuada.
Why use exception handling rather than checking for every error in advance? Select all · todos that apply. · ¿Por qué usar manejo de excepciones en lugar de verificar cada error por adelantado? Seleccione todos los que apliquen.
The benefits are correctness and clarity. Speed is not one of them; handling adds a little overhead, which is worth paying. · Los beneficios son la corrección y la claridad. La velocidad no es uno de ellos; el manejo añade una sobrecarga pequeña, pero vale la pena pagarla.
The TRY structure
- The TRY block holds the code that might fail. If it runs without error, the EXCEPT blocks are skipped entirely.
- If an exception occurs, execution jumps immediately to the first matching EXCEPT block. The rest of the TRY block does not run.
- A FINALLY block runs whether or not an exception happened, which makes it the right place for cleanup such as closing a file.
One path when all is well, another when it is not, and one that always runs
La estructura TRY
TRY
OPENFILE "data.txt" FOR READ
READFILE "data.txt", line
CLOSEFILE "data.txt"
EXCEPT FileNotFound
OUTPUT "Sorry, the file does not exist."
EXCEPT ReadError
OUTPUT "Sorry, there was an error reading the file."
FINALLY
OUTPUT "Finished attempting to read."
ENDTRY
- El bloque TRY contiene el código que podría fallar. Si se ejecuta sin errores, los bloques EXCEPT se saltan completamente.
- Si ocurre una excepción, la ejecución salta inmediatamente al primer bloque EXCEPT coincidente. El resto del bloque TRY no se ejecuta.
- Un bloque FINALLY se ejecuta sí o sí, independientemente de si ocurrió una excepción, lo que lo convierte en el lugar adecuado para tareas de limpieza como cerrar un archivo.

Un camino cuando todo va bien, otro cuando no, y uno que siempre se ejecuta
How exception handling flows · Flujo del manejo de excepciones
Step through what happens when code fails. The exception jumps out of the normal flow to a handler, FINALLY cleans up either way, and the program carries on instead of crashing. · Paso a paso de lo que ocurre cuando falla el código. La excepción salta del flujo normal hacia un manejador, FINALLY limpia en cualquier caso, y el programa continúa en lugar de fallar.
Match each exception-handling keyword to its job. · Asocie cada palabra clave de manejo de excepciones con su función.
TRY guards the risky code, EXCEPT catches, FINALLY cleans up either way, RAISE throws an error to be caught. · TRY protege el código riesgoso, EXCEPT captura, FINALLY limpia en cualquier caso, RAISE lanza un error para ser capturado.
A FINALLY block: · Un bloque FINALLY:
FINALLY always runs, making it ideal for cleanup such as closing files. · FINALLY siempre se ejecuta, lo que lo hace ideal para tareas de limpieza como cerrar archivos.
The block that runs whether or not an exception occurred, making it right for closing files, is ____. · El bloque que se ejecuta haya o no haya ocurrido una excepción, haciéndolo adecuado para cerrar archivos, es ____.
Cleanup must happen on both paths. Putting CLOSEFILE only in the TRY block means it is skipped exactly when an error left the file open. · La limpieza debe ocurrir en ambos caminos. Poner CLOSEFILE solo en el bloque TRY significa que se omite exactamente cuando un error deja el archivo abierto.
Worked example: trace the flow
- In the code above, the file does not exist. State exactly what is output and what is skipped.
OPENFILEraises FileNotFound, so execution leaves the TRY block immediately: theREADFILEandCLOSEFILElines never run.- The
FileNotFoundEXCEPT block runs, outputting "Sorry, the file does not exist." TheReadErrorblock does not run, because only the first matching handler is used. - The FINALLY block runs, outputting "Finished attempting to read."
- The mark most often lost is noticing that the rest of the TRY block is abandoned.
Ejemplo resuelto: trazar el flujo
- En el código anterior, el archivo no existe. Indica exactamente qué se imprime y qué se omite.
OPENFILEgenera una FileNotFound, por lo que la ejecución abandona el bloque TRY inmediatamente: las líneasREADFILEyCLOSEFILEnunca se ejecutan.- Se ejecuta el bloque EXCEPT
FileNotFound, imprimiendo "Sorry, the file does not exist.". El bloqueReadErrorno se ejecuta, porque solo se utiliza el primer manejador coincidente. - Se ejecuta el bloque FINALLY, imprimiendo "Finished attempting to read.".
- El punto que más suele perderse es notar que el resto del bloque TRY se abandona.
The file in the TRY block does not exist. Put what happens in order. · El archivo en el bloque TRY no existe. Coloque lo que sucede en orden.
Only the first matching handler runs, and FINALLY runs either way. The skipped remainder of the TRY block is the mark most often missed. · Solo se ejecuta el primer manejador coincidente, y FINALLY se ejecuta en cualquier caso. El resto omitido del bloque TRY es la marca que más se pasa por alto.
Raising an exception
- A subroutine that detects a problem it cannot sensibly deal with can raise 抛出 an exception, passing responsibility to whoever called it:
- This is the right design when the subroutine knows something is wrong but not what should be done about it. A division routine knows the divisor is zero; only the caller knows whether to ask the user again, use a default, or abandon the calculation.
Levantar una excepción
- Una subrutina que detecta un problema que no puede gestionar razonablemente puede levantar una excepción, transfiriendo la responsabilidad a quien la llamó:
IF b = 0 THEN RAISE DivideByZero
- Este es el diseño correcto cuando la subrutina sabe que algo está mal pero no sabe qué debería hacerse al respecto. Una rutina de división sabe que el divisor es cero; solo el llamador sabe si debe pedir al usuario que lo reintente, usar un valor predeterminado o abandonar el cálculo.
A subroutine uses RAISE to: · Una subrutina usa RAISE para:
RAISE throws an exception up to the caller, which can catch it with EXCEPT. · RAISE lanza una excepción hacia el llamador, quien puede capturarla con EXCEPT.
Why would a division subroutine RAISE an exception instead of handling a zero divisor itself? · ¿Por qué una subrutina de división lanzaría una excepción en lugar de manejar un divisor cero ella misma?
Ask the user again, use a default, or abandon the calculation: only the calling code has the context to choose. · Solicitar nuevamente al usuario, usar un valor predeterminado o abandonar el cálculo: solo el código de llamada tiene el contexto para elegir.
Where to handle it
- Handle an exception close to where it occurs when the response is simple and local: print a message, use a default, ask the user to try again.
- Handle it higher up when the decision belongs to a larger part of the program: whether to abandon a whole transaction, roll back a change, or tell the user the operation failed.
- The rule of thumb: catch it at the level that has enough information to decide what to do, not at the level that first notices.
Dónde manejarla
- Maneja una excepción cerca de donde ocurre cuando la respuesta es simple y local: imprimir un mensaje, usar un valor predeterminado, pedir al usuario que lo intente de nuevo.
- Manejala más arriba cuando la decisión corresponde a una parte mayor del programa: si se debe abandonar toda la transacción, deshacer un cambio o informar al usuario de que la operación falló.
- Regla general: captúrala al nivel que tenga suficiente información para decidir qué hacer, no al nivel que la note por primera vez.
Worked example: what not to do
- A student writes
EXCEPT: (do nothing)around a whole program so it never crashes. Explain why this is poor practice. - The exception is swallowed: the program continues as though nothing went wrong, so it carries on with missing or invalid data and produces wrong results instead of an obvious failure.
- A silent failure is harder to diagnose than a crash, because there is no message and no indication of where it happened.
- Catching every exception in one place also means the specific error type is lost, so no sensible response can be chosen. A handler should catch a specific exception and actually respond to it.
Ejemplo resuelto: qué no hacer
- Un estudiante escribe
EXCEPT: (do nothing)alrededor de todo un programa para que nunca colapse. Explica por qué esto es una mala práctica. - La excepción es absorbida: el programa continúa como si nada hubiera pasado, continuando con datos faltantes o inválidos y produciendo resultados incorrectos en lugar de mostrar un fallo obvio.
- Un fallo silencioso es más difícil de diagnosticar que un colapso, porque no hay mensaje ni indicación de dónde ocurrió.
- Capturar todas las excepciones en un solo lugar también significa que se pierde el tipo específico de error, por lo que no se puede elegir una respuesta sensata. Un manejador debe capturar una excepción específica y realmente responder ante ella.
Silently "swallowing" an exception (catching it but doing nothing) hides real errors and makes debugging hard — you should handle it or at least log it. · Silenciar "tragar" una excepción (capturarla pero no hacer nada) oculta errores reales y dificulta la depuración — se debe manejar o al menos registrar.
An empty handler hides the very problems you need to find; always respond or record the error. · Un manejador vacío oculta los mismos problemas que necesita encontrar; siempre responda o registre el error.
Marks that slip away
- When an exception occurs, the rest of the TRY block is skipped. Say so when tracing.
- Only the first matching EXCEPT runs, not all of them.
- FINALLY always runs, error or no error, which is what makes it right for closing files.
- Do not catch an exception and do nothing. A swallowed error is worse than a crash, because the program continues with bad data.
Puntos que suelen pasarse por alto
- Cuando ocurre una excepción, el resto del bloque TRY se omite. Menciónalo al trazar.
- Solo se ejecuta el primer EXCEPT coincidente, no todos.
- FINALLY siempre se ejecuta, con error o sin él, lo que lo hace ideal para cerrar archivos.
- No captures una excepción y no hagas nada. Un error absorbido es peor que un colapso, porque el programa continúa con datos incorrectos.
You've got it
- an exception is a run-time error; handling it lets a program respond instead of crashing, covers errors that cannot be prevented in advance, and separates normal code from error handling
- TRY holds the risky code; on an error the rest of it is skipped and the first matching EXCEPT runs; FINALLY runs either way, so cleanup belongs there
- a subroutine that cannot decide the response should RAISE the exception for its caller
- handle it close by for a simple local response, higher up when the decision needs a wider view; never catch it and do nothing
Ya lo tienes
- una excepción es un error en tiempo de ejecución; manejarla permite que un programa responda en lugar de colapsar, cubre errores que no pueden prevenirse con antelación y separa el código normal del manejo de errores
- TRY contiene el código arriesgado; ante un error, el resto se omite y se ejecuta el primer EXCEPT coincidente; FINALLY se ejecuta de cualquier forma, por lo que la limpieza debe ir allí
- una subrutina que no puede decidir la respuesta debe levantar la excepción para su llamador
- manéjala cerca para una respuesta local simple, más arriba cuando la decisión requiere una visión más amplia; nunca la captures y no hagas nada