Skip to Content
Python for Beginners: Write Code That Actually Runs, Then Make It Better
Beginner
0 likes
Courses
Python for Beginners: Write Code That Actually Runs, Then Make It Better

Python Try and Except: Handling Errors Properly

Catch errors with try and except, catch the specific error instead of everything, and use else, finally and raise. You'll finish with an input loop that keeps asking until the answer is valid.

Course content

Sign in to save your progress.

Course Home

Python Try and Except: Handling Errors Properly

try and except let your program deal with an error instead of crashing. You put the risky code in try, and what to do if it fails in except. Used well, it turns a crash into a clear message. Used badly, it hides bugs you need to see.

Skip ahead: If you already catch specific exceptions and know why a bare except: is a bad idea, continue to the quiz for this section.

Why this matters

Some errors are bugs: a typo, wrong logic. Those you fix in the code. Other errors are expected: a user types "ten" instead of 10, a file is missing, a network is down. Those are not your mistakes, but your program still has to handle them. try and except is for the second kind. Mixing up the two is how people end up hiding real bugs.

The basic form

text = input("Enter a whole number: ")

try:
    number = int(text)
    print(f"Double that is {number * 2}")
except ValueError:
    print(f"'{text}' is not a whole number.")

If int() fails, Python jumps straight to the except ValueError block. The program continues instead of crashing.

Catch the specific error

Always name the error you expect. Different problems need different answers:

def safe_divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        print("Cannot divide by zero.")
        return None
    except TypeError:
        print("Both values must be numbers.")
        return None

print(safe_divide(10, 2))     # 5.0
print(safe_divide(10, 0))     # message, then None
print(safe_divide(10, "2"))   # message, then None

⚠ Warning: Do not write a bare except: or except Exception: pass just to make errors go away. It catches everything, including your own typos, and silently continues with wrong data. The program "works", the results are wrong, and you have no message to tell you why. If you are not sure what can go wrong, let it crash while you are developing and read the traceback.

else and finally

text = "42"

try:
    number = int(text)
except ValueError:
    print("Not a number.")
else:
    print(f"Converted fine: {number}")   # runs only if no error
finally:
    print("Check finished.")             # always runs

else keeps the "success" code out of the try block, so you only catch errors from the line you meant to protect. finally always runs, error or not. It is used for clean-up, like closing something you opened.

A real-world example: asking until the input is valid

def ask_quantity():
    while True:
        text = input("Quantity (1-100): ").strip()
        try:
            quantity = int(text)
        except ValueError:
            print("Please type a whole number, like 5.")
            continue
        if 1 <= quantity <= 100:
            return quantity
        print("The quantity must be between 1 and 100.")

qty = ask_quantity()
print(f"Ordering {qty} items.")

This combines almost everything from this tutorial: a function, a while loop, input, conversion, an if statement, and try/except. Notice that the range check is an if statement, not an exception. A number like 500 converts fine; it is just not allowed. That is a rule, so it is checked with if.

Raising your own errors

def set_discount(percent):
    if not 0 <= percent <= 50:
        raise ValueError("Discount must be between 0 and 50 percent.")
    return percent

try:
    set_discount(80)
except ValueError as error:
    print("Rejected:", error)

raise stops the function and reports a problem to whoever called it. It is better than quietly accepting a wrong value. Fail loudly and early. A loud error today beats a wrong invoice next month.

Common mistakes

  • Catching everything. Name the specific exception.
  • Huge try blocks. Wrap only the line that can fail, so you know what failed.
  • Hiding the error. At least print or log what went wrong. except ValueError as error: gives you the message.
  • Using try/except for logic. Use if statements for rules you can check in advance.

💡 Tip: Ask one question before adding try/except: "If this fails, what should the program do instead?" If you do not have an answer, you are not ready to catch the error. Let it crash and find out more first.

What happens if you skip this step

Either your programs crash in front of users at the first bad input, or you overcorrect and wrap everything in except: pass, which is worse. Crashes at least tell you something is wrong. Hidden errors just produce bad results quietly. I would rather have the crash. Full stop.

Quick check: in the quantity example, why is "500" handled with an if statement and not with except?

About

Catch errors with try and except, catch the specific error instead of everything, and use else, finally and raise. You'll finish with an input loop that keeps asking until the answer is valid.

Duration
5 min
Last update
09/08/2026
Was this helpful?
​ 0 ​ 0

Comments (0)

Sign in to comment

No comments yet.