Saturday, October 31, 2026 New tutorials published every day
Home
Tutorials
Core PHP PHP Course JavaScript React & Next.js Python WordPress Artificial Intelligence
Free Tools
JSON Formatter Base64 Encoder / Decoder Password Generator Text to QR Code Generator Word Counter Case Converter Age Calculator Color Converter Number to Words All Free Tools
Projects
PHP Projects — all projects
Students
Course Registration Download Syllabus Verify Certificate Student Leaderboard
Resources
Search tutorials About CodingCush Contact
More
Login
Python

Python Error Handling: try, except and finally Explained with Examples

Learn Python error handling with try, except, else and finally. Simple examples for catching errors, cleaning up files and writing code that never crashes.

Python error handling uses a try block to run risky code, an except block to catch and handle any error that happens, and a finally block for code that must run no matter what, such as closing a file. Instead of letting your whole programme crash with a red error message, you catch the problem, show a friendly message, and keep the rest of your code running safely.

What Is Error Handling in Python?

Every programme meets problems sooner or later. A user types letters where a number should go. A file you expected is missing. A network connection drops halfway through a download. In Python, these problems are called exceptions, and when one happens Python normally stops the programme and prints a long traceback — helpful for you as the developer, terrifying for your user.

Error handling is simply your plan for those moments. You tell Python: "Try this code, and if something goes wrong, do this instead of crashing." It is a bit like wearing a seatbelt. You do not plan to crash, but you are very glad it is there on the one day you need it.

Python gives you four keywords for this job: try, except, else and finally. The official tutorial walks through the same ideas in the Python documentation on errors and exceptions, and it is worth keeping that page open while you learn.

The Basic try and except Block

The simplest form needs only two parts. Put the risky code inside try, and put your rescue plan inside except:

try:
    number = int(input("Enter a number: "))
    print("You entered:", number)
except ValueError:
    print("That was not a valid number. Please try again.")

If the user types 42, everything works and the except block is skipped completely. If the user types hello, int() raises a ValueError, Python jumps straight into the except block, and the friendly message appears instead of a crash. The programme keeps running afterwards, which is the whole point.

Notice that we named the exact error, ValueError. Python has many built-in exception types, and the full list of built-in exceptions in the documentation shows what each one means. Catching a specific error is almost always better than catching everything, because it stops you from hiding real bugs by accident.

Catching Different Errors in Different Ways

Real code can fail in more than one way, and each failure may need a different response. You can stack several except blocks under one try, and Python uses the first one that matches:

try:
    numerator = int(input("Enter the top number: "))
    denominator = int(input("Enter the bottom number: "))
    result = numerator / denominator
    print("Result:", result)
except ValueError:
    print("Please enter whole numbers only.")
except ZeroDivisionError:
    print("You cannot divide by zero. Even Python has limits.")

Here, typing letters triggers the first block, while typing 0 as the denominator triggers the second. Each problem gets a message that actually describes it, which makes your programme far easier to use — and far easier to debug later.

You can also catch several errors with one block by grouping them in brackets, and you can read the error message itself with as:

try:
    age = int(input("Enter your age: "))
    print("Next year you will be", age + 1)
except (ValueError, TypeError) as error:
    print("Something went wrong:", error)

The variable error holds Python's own description of the problem. Printing it during development is a great habit, because it tells you exactly which line complained and why.

Official Python tutorial documentation page on input and output, the chapter before Errors and Exceptions
The official Python tutorial — reading and writing files is where most beginners meet their first exceptions.

The else Block: Code That Runs Only on Success

The optional else block runs only when the try block finishes with no error at all. Beginners often ask why it exists, when they could simply put the code at the end of try. The answer is clarity and safety: code inside try is protected by your except blocks, so an error there could be caught and hidden by mistake. Code in else is not protected, so any error it raises will still surface properly.

try:
    file = open("scores.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("The scores file could not be found.")
else:
    print("File loaded successfully.")
    print(content)
    file.close()

If the file opens and reads cleanly, the else block runs. If the file is missing, only the except message runs. This pattern pairs naturally with our guide on how to read and write files in Python, where the same open, read and close steps are explained in full.

The finally Block: Code That Always Runs

The finally block is the tidy-up crew. Its code runs whether the try block succeeded, failed, or even returned early. That makes it perfect for releasing resources: closing files, closing network connections, or unlocking something you locked.

try:
    file = open("notes.txt", "r")
    print(file.read())
except FileNotFoundError:
    print("notes.txt does not exist yet.")
finally:
    print("Finished — cleaning up now.")

Whatever happens above, that final message prints. In real projects the finally block usually closes the file instead of printing, so the file is never left open by accident. An open file that never closes can lock the file for other programmes and quietly waste memory, which is nobody's idea of fun.

try, except, else and finally Compared

Here is the whole flow in one table:

Block When it runs Typical job
try Always, first Holds the risky code you want to protect
except Only when a matching error happens Handles the problem with a message or a fallback
else Only when no error happens Runs follow-up code that depends on success
finally Always, last Cleans up: closes files and connections

A useful way to remember it: try is the attempt, except is the rescue, else is the celebration, and finally is switching the lights off when you leave — it happens every single time.

Raising Your Own Exceptions

Sometimes your own code needs to report a problem. Use the raise keyword to trigger an exception on purpose, usually when input breaks a rule your programme depends on:

def set_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative.")
    print("Age set to", age)

try:
    set_age(-5)
except ValueError as error:
    print("Error:", error)

Writing small helper functions like this is much easier once functions feel natural, so if they still feel new, work through our beginner-friendly guide to Python functions explained with examples first. Raising clear errors early stops bad data from travelling deep into your programme, where it becomes much harder to trace.

Common Mistakes Beginners Make

Catching everything with a bare except. Writing except: with no error type catches every possible problem, including typos and real bugs, and then hides them. Your programme looks calm while quietly doing the wrong thing. Name the error you expect instead.

Leaving the except block empty. An except block that does nothing is like a smoke alarm with the batteries removed. At minimum, print or log what went wrong.

Putting too much code in try. Keep the try block small, covering only the lines that can actually fail. A huge try block makes it hard to know which line caused the error.

Forgetting finally for cleanup. If you open something inside try, close it in finally (or use a with statement for files), so it closes even when an error interrupts you.

Frequently Asked Questions

What is the difference between try and finally in Python?

The try block holds code that might raise an error. The finally block holds cleanup code that runs after everything else, whether an error happened or not.

Can I use try without except in Python?

Yes, if you pair it with finally. A try and finally combination is valid and is used purely for guaranteed cleanup. A try block must have at least one except or a finally after it.

What happens if an error is not caught?

Python stops the programme and prints a traceback showing where the error happened. Nothing after that line runs, which is why catching expected errors makes your programme feel much more polished.

Should I catch all exceptions with except Exception?

Only as a last-resort safety net, for example at the very top of a programme, and always log the error when you do. For normal code, catch the specific exception you expect, such as ValueError or FileNotFoundError.

Conclusion

Error handling is what separates a script that works on a good day from a programme you can trust every day. Use try for risky code, except to handle specific problems with clear messages, else for code that should only run on success, and finally for cleanup that must always happen. Start small — wrap your user input and file reading first — and your Python programmes will instantly feel calmer, kinder and far more professional.

Lavkush
Written by

Lavkush Super Admin

Lavkush Kumar is a software developer with over 6 years of experience turning ideas into websites and web applications. He holds a Master of Computer Applications (MCA) degree and enjoys building for the web, exploring new tools, and sharing what he learns along the way.

Through CodingCush, Lavkush creates easy-to-follow tutorials and practical guides to help students and beginners learn software development without feeling overwhelmed. His approach is simple: learn by doing, build real projects, and keep improving one step at a time.

Whether you’re just starting out or looking to sharpen your skills, CodingCush is all about making learning practical, beginner-friendly, and fun.

0 Comments

Leave a Comment