Handle errors and read files

Learn what exceptions are and how to work with a text file safely.

An exception is an error that occurs while a program runs. try and except let you handle expected failures, such as invalid numeric input. When working with files, the with statement closes the file automatically after the block.

Convert input safely

python · static example

text = "42"

try:
    count = int(text)
    print(count + 1)
except ValueError:
    print("Please provide a whole number.")

This example converts a text value. A real input form should validate the value and explain what is accepted.

Sample output
43

Labeled sample only — nothing was run on this page.

Write a small text file

python · static example

with open("notes.txt", "w", encoding="utf-8") as file:
    file.write("Python practice")

The `w` mode creates or replaces the file. Use a different mode if you need to preserve existing content.

    Handle errors and read files · Python for Beginners | Nestify Campus