Exceptions · Excepciones
When things go wrong
- A runtime error normally crashes the program.
- An exception is Python's signal that something went wrong.
- Exception handling lets you catch it and keep running.
Cuando las cosas fallan
- Un error de ejecución normalmente detiene el programa.
- Una excepción es la señal de Python de que algo ha salido mal.
- El manejo de excepciones te permite capturarla y continuar ejecutando.
try / except
- Put risky code in a
try:block. - If it raises an exception, the
except:block runs instead of crashing. - If nothing goes wrong, the
exceptblock is skipped.
try / except
- Coloca el código riesgoso en un bloque
try:. - Si se produce una excepción, se ejecuta el bloque
except:en lugar de que el programa se detenga. - Si no ocurre nada malo, se omite el bloque
except.
try:
number = int("not a number")
except ValueError:
number = 0
print(number)
Catch the right error
- Name the type of error you expect:
except ValueError:. ValueErroris bad text for a number;ZeroDivisionErroris divide by zero.- Catching a specific type means you do not hide other bugs.
Captura el error correcto
- Nombra el tipo de error que esperas:
except ValueError:. ValueErrorindica texto inválido para un número;ZeroDivisionErrorindica división por cero.- Capturar un tipo específico significa que no ocultas otros errores.
try:
print(10 / 0)
except ZeroDivisionError:
print("Cannot divide by zero")
finally and raise
- A
finally:block always runs, error or not — good for cleanup. raiselets you signal an error on purpose.raise ValueError("message")stops the code unless something catches it.
finally y raise
- Un bloque
finally:siempre se ejecuta, con o sin error — ideal para tareas de limpieza. raisete permite generar un error a propósito.raise ValueError("message")detiene la ejecución a menos que algo lo capture.
try:
raise ValueError("bad value")
except ValueError as e:
print("Caught:", e)
finally:
print("Always runs")
Why it matters
- A robust program should not crash on bad input.
- Handling exceptions lets it warn the user and carry on.
- It also makes sure files and other resources are closed cleanly.
Por qué es importante
- Un programa robusto no debería detenerse ante una entrada incorrecta.
- Manejar las excepciones le permite advertir al usuario y continuar.
- También asegura que los archivos y otros recursos se cierren correctamente.
Common mistakes
- Catch a specific error (
except ValueError:), not a bareexcept:. - Put only the risky line inside the
try.
Errores comunes
- Captura un error específico (
except ValueError:), no unexcept:genérico. - Coloca solo la línea riesgosa dentro del
try.
Now you try
- Use
try/except(andraisein the last task). - Press Check answer to test your code.
Ahora tú intentas
- Usa
try/except(yraiseen la última tarea). - Pulsa Check answer para probar tu código.
try / except
Code runs in try; if it fails, control jumps to except. · El código se ejecuta en try; si falla, el control salta a except.
Write safe_int(text) that returns · retornos int(text). If the text is not a valid number, catch the ValueError and return -1 instead. · Escribe safe_int(text) que devuelva int(text). Si el texto no es un número válido, captura la ValueError y devuelve -1 en su lugar.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Write divide(a, b) that returns · retornos a / b. If b is 0, catch the ZeroDivisionError and return None instead. · Escribe divide(a, b) que devuelva a / b. Si b es 0, captura la ZeroDivisionError y devuelve None en su lugar.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Write withdraw(balance, amount). If amount is more than balance, raise ValueError. Otherwise return · retorno the new balance (balance - amount). · Escribe withdraw(balance, amount). Si amount es mayor que balance, raise ValueError. De lo contrario, devuelve el nuevo saldo (balance - amount).
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.