Contenido del curso

Try and Except for Python Errors

Resumen

Handling errors in Python with try and except is what separates a fragile script from production-ready software. When your code talks to a server, asks the user for input, or performs math, something will eventually break. And you want to decide what happens next, not let Python decide for you.

This guide walks you through the fundamentals of try and except, shows real failures (like dividing by zero or receiving text instead of a number), and explains how to capture specific exceptions instead of swallowing every error blindly.

Why does Python need try and except for error handling?

When you build software, you constantly transform or receive data. A news server might be down, a user might type a letter where you expected a number, or a division might land on zero. Without protection, your program crashes and shows a scary traceback meant for developers, not users [00:09].

Imagine a small program that asks for two numbers and divides them:

python a = int(input("Type a number: ")) b = int(input("Type another number: ")) result = a / b print(result)

With 10 and 2, you get 5.0. With 10 and 0, Python throws a ZeroDivisionError and stops everything [01:32]. That is exactly the moment where try and except step in.

What does try and except do in Python? try runs code that might fail. except catches the failure and lets you respond gracefully instead of crashing. Together they keep your program alive and your users informed.

How do you write your first try except block?

The pattern is simple: wrap the risky line inside try, then handle the failure inside except. Here is the same division, now protected:

python try: result = a / b print(result) except Exception as e: print(e)

Using Exception as e captures any error and stores it in the variable e, so you can inspect or print it [02:24]. Exception is the base class that tags every error in Python, which is why it catches almost anything.

If you run the program with 10 and 0, instead of the ugly traceback you see a clean message: division by zero. You just turned a crash into a controlled response.

What happens with the variables when an error occurs?

If the failure happens before a variable is assigned, that variable does not exist later. In the example, result was never created when the division failed, so printing it outside the block raises a second error [02:55]. A safe trick is to define result = None before the try, so the rest of the code keeps working.

When should you use specific exceptions instead of Exception?

Catching everything with Exception is tempting, but it hides bugs. The recommended practice is to catch the exact exception you expect. Python tells you which class to use: when the user types hola instead of a number, you see ValueError: invalid literal for int [04:18]. When dividing by zero, you see ZeroDivisionError.

Knowing this, you can write targeted handlers:

python try: a = int(input("Type a number: ")) b = int(input("Type another number: ")) result = a / b print(result) except ValueError: print("What you typed is not a valid number") except ZeroDivisionError: print("Division by zero is not allowed")

Now each error gets its own message. The user sees something useful, and you, as the developer, keep visibility into what actually failed [06:45].

What is the difference between Exception and ZeroDivisionError? Exception is the generic parent class that catches almost any error. ZeroDivisionError is a specific child class that only triggers when you divide by zero. Specific exceptions make debugging easier and avoid hiding unrelated bugs.

What are the best practices for using try except in Python?

Three recommendations will keep your error handling clean and useful [07:35]:

  • Do not overuse it. Only wrap code where you genuinely expect failures. Sprinkling try everywhere makes your code unreadable.
  • Be specific. Catch the real exception class instead of Exception. This makes debugging faster and lets you craft accurate messages per error type.
  • Always log or print the error. Silent failures are the worst kind of bug, especially on servers, because they hide problems deep inside your system.

How can you apply try except to a real API call?

A practical challenge: take your method that connects to the News API and wrap it in try and except. Replace the API key with an invalid one, catch the error, and show the user a message saying the connection failed because the credentials are not valid [08:30]. That is the same pattern you will use in production: anticipate the failure point, catch the right exception, and communicate clearly.

What error did you run into when testing your News API call? Drop it in the comments and share how you handled it.