Contenido del curso
Calidad y Profesionalismo del Código
Manejo de Datos y Recursos
Optimización y Pruebas
Creación de Aplicaciones de Consola
- 19

UV: Faster Python Dependency Management
07:17 min - 20

How Python Modules Keep Your Code Organized
07:14 min - 21

Organizing Python Code Into Packages
09:06 min - 22

Función enumerate en Python para indexar listas automáticamente
09:31 min - 23

Filtrado de listas con filter en Python
11:44 min - 24

Función map para calcular tiempo de lectura en Python
08:59 min - 25

Conexión de OpenAI API con variables de entorno en Python
11:17 min
Custom Exceptions for Python API Errors
Resumen
Mastering try, except, and finally is just the start. The real leap in your Python skills happens when you learn to create your own exceptions, a key practice for building software that other developers can actually understand and extend.
When your API returns an error, you no longer want to send back an empty JSON list and pretend nothing happened. You want to raise a specific error, like NewsAPIError, so whoever consumes your function decides how to react.
What does raise do in Python and when should you use it?
The keyword raise is what lets you throw a new exception on purpose. It stops the execution of your code immediately, just like Python does when it finds an error on its own.
Imagine you want to forbid dividing by a specific number, say when b == 2. Inside your function you can write raise Exception("No está permitido el cálculo por dos"). The moment that line runs, Python halts the normal flow, executes the finally block, and prints the traceback with your custom message.
What is raise in Python? It is a keyword that interrupts execution and throws an exception of the type you choose, so the calling code can catch it with
except.
How do you create a custom exception class in Python?
Raising a generic Exception works, but it is too broad. A cleaner approach is to define a subclass that describes exactly what went wrong.
python class DivisionError(Exception): """Error en operación""" pass
Now instead of raise Exception(...) you write raise DivisionError("No está permitido el cálculo por dos"). The behavior is the same, but developers using your code can catch DivisionError specifically, without swallowing every other error in the language.
That distinction matters. When you except Exception, you catch literally everything, including bugs you did not anticipate. When you catch DivisionError, you only handle the case you care about.
What are the four key clauses of error handling in Python?
Before moving on, here is the full picture of the building blocks you are combining.
try: wraps the code that might fail.raise: stops execution and throws an error of the type you specify.except: catches a specific error type, or all of them if you useException.finally: always runs, whether an error happened or not.
Placing a print outside the finally block is a quick way to confirm that unexpected errors really do skip the rest of your code.
How do you apply custom exceptions in a real News API client?
Let's bring this into a real project. The idea is to group every error of the application under a common parent, so the codebase stays organized as it grows.
python class NewsSystemError(Exception): """Error general en la app""" pass
class APIKeyError(NewsSystemError): """Error cuando la API key es inválida""" pass
The parentheses next to the class name define the inheritance. APIKeyError inherits from NewsSystemError, which inherits from Exception. That hierarchy lets another developer catch NewsSystemError to handle anything related to your app, or catch APIKeyError to react only to invalid credentials.
How do you replace empty returns with a raised exception?
In the original News API client, when the request failed the function returned {"articles": []}. That is a silent failure, the worst kind. The fix is to raise the new exception instead.
python raise APIKeyError("Ocurrió un error, no se pudo conectar con la API")
Now the function does not lie about its result. It tells the caller something broke, and the caller decides what to do.
Why is raising better than returning an empty list? Because an empty list looks like a valid response. Raising an exception forces the caller to handle the failure explicitly, instead of debugging a confusing empty result later.
How do you catch your custom exception where the function is used?
Once the function can raise APIKeyError, every place that calls it must be ready to handle it. Inside fetch_news you wrap the call in try and capture the exception with as e to access its message.
python response_data = None try: response_data = client.get_news() except APIKeyError as e: print(e)
if response_data is None: return
Two details make this code robust:
- Initialize
response_data = Nonebefore thetry, so the variable always exists even if the request fails. - Validate with
if response_data is Nonebefore using it, to avoid a second crash on top of the first.
With this pattern, breaking the API key on purpose no longer floods the console with a NameError about response_data. You only see the clean message: Ocurrió un error, no se pudo conectar con la API.
Why does this matter when you work in a team?
The payoff shows up when you are not the only person using your code. By raising typed exceptions with clear names and docstrings, you give your teammates the freedom to decide what to display, whether to retry, or whether to suppress the error entirely.
You stop dictating behavior and start exposing intent. That is the difference between a script and a library someone else can build on.
Now it is your turn: design a custom exception that fits the News API client and share it in the comments. What scenario would you cover that is not handled yet?